在使用SWR发起请求时遇到了typescript问题

12

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

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 hook

的翻译是:

SWR钩子

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

20

这是fetch函数的TypeScript签名:

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

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

fetcher();

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

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

然后,您可以使用扩展语法来调用fetch API。扩展运算符的参数不符合fetch函数签名的要求(参数数量不能为零或大于两个),因此tsc会报错。

因此,最好像这样修改它:

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

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


既然你除了前两个参数之外没有使用其他的参数,那么干脆就把 ...args 省略掉不用会更好吧? - SimonW
@SimonW 是的,我不确定 fetcher 是否需要其他参数。所以我保留了 ...args - Lin Du
你好,你有使用示例吗? 我现在还不确定如何调用fetcher并传递init对象及其值。例如: const {data, error} = useSWR("/some/path", fetcher("some/path", {headers: {}}))正确的方式是什么? - chalo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接