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

gab*_*iso 6 javascript typescript reactjs next.js swr

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

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

这是我的 SWR 提取器函数,这是我得到的错误

[tsserver 2556] [E] Expected 1-2 arguments, but got 0 or more.
Run Code Online (Sandbox Code Playgroud)

驻波钩

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

sli*_*wp2 10

这是fetch函数的TypeScript 签名:

declare function fetch(input: RequestInfo, init?: RequestInit): Promise<Response>;
Run Code Online (Sandbox Code Playgroud)

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

fetcher();
Run Code Online (Sandbox Code Playgroud)

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

fetcher("localhost", {}, {}, {});
Run Code Online (Sandbox Code Playgroud)

然后,您使用扩展语法来调用fetch API。spread 的参数不满足 fetch 的函数签名(参数不能为零或大于两个),所以 tsc 报错。

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

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

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