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

解决方法

这是 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"

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...