向SWR请求时打字稿出现问题

时间:2020-10-04 20:35:46

标签: javascript reactjs typescript next.js swr

我想知道下面传递给我的函数的args是什么类型

const fetcher = async (...args) => {                                
~_  0   const res = await fetch(...args);                                                                       
    1                                            
~   2   return res.json();                                                                                      
    3 };  

这是我的SWR提取程序功能,这是我收到的错误

[tsserver 2556] [E] Expected 1-2 arguments, but got 0 or more.

SWR钩子

const { error, data } = useSWR(`/api/albums/list/${user.id}`, fetcher)

1 个答案:

答案 0 :(得分:8)

这是 fetch 函数的 TypeScript 签名:

declare function fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;

如果您使用函数 rest parameters ...args,您的 fetcher 函数可以像这样使用零参数调用并且 tsc 不会报告错误。

fetcher();

或者,很多参数(比如四个参数):

fetcher("localhost", {}, {}, {});

然后,您使用 spread syntax 调用 fetch API。 spread 的参数不满足 fetch 的函数签名(参数不能为 0 或大于 2),所以 tsc 报错。

所以你最好像这样修改它:

const fetcher = async (
  input: RequestInfo,
  init: RequestInit,
  ...args: any[]
) => {
  const res = await fetch(input, init);
  return res.json();
};

软件包版本:"typescript": "^4.1.3"

相关问题