TypeScript 错误 - 需要 1-2 个参数,但有 0 个或更多。TS2556

fpo*_*g01 3 javascript typescript reactjs

我在 JavaScript 中使用了这条语句,但是当我尝试在 TypeScript 项目中使用它时,出现错误。它在抱怨 fetch(...args)

const fetcher = (...args) => fetch(...args).then(response => response.json());

Expected 1-2 arguments, but got 0 or more.  TS2556
Run Code Online (Sandbox Code Playgroud)

cap*_*ian 13

这应该可以帮助您:

const fetcher = (...args: [input: RequestInfo, init?: RequestInit | undefined]) => fetch(...args).then(response => response.json());

Run Code Online (Sandbox Code Playgroud)

您应该为 明确键入参数fetch。它需要 1-2 个参数。

如果您想使用rest运算符,您应该告诉 TS,您还期望在高阶函数中有两个参数

更新

通用方法。如果要获取任何函数的参数类型,只需使用Parameters util。

type FetchParameters = Parameters<typeof fetch>
Run Code Online (Sandbox Code Playgroud)

  • 不知道为什么 @jcatz 删除了他的响应,因为 `const fetcher = (...args:Parameters&lt;typeof fetch&gt;) =&gt; fetch(...args).then(response =&gt; response.json());` 是一个很好的解决方案,因为它使用Parameters &amp; typeof 自动为您排列参数类型。 (5认同)