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

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

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

Expected 1-2 arguments, but got 0 or more.  TS2556

回答

这应该可以帮助您:

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

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

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

更新

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

type FetchParameters = Parameters<typeof fetch>

  • Not sure why @jcatz deleted his response, as `const fetcher = (...args: Parameters<typeof fetch>) => fetch(...args).then(response => response.json());` is a nice solution, as it lines up the parameters types automatically for you using Parameters & typeof.

以上是TypeScript错误-需要1-2个参数,但有0个或更多。TS2556的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>