6

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

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)
4

1 回答 1

13

这是fetch函数的 TypeScript 签名:

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

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

fetcher();

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

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

然后,您使用扩展语法调用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"

于 2021-01-04T11:55:01.263 回答