首页 > 解决方案 > 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

标签: javascriptreactjstypescript

解决方案


这应该可以帮助您:

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>

推荐阅读