简体   繁体   English

TypeScript 错误 - 预期为 1-2 arguments,但得到 0 或更多。 TS2556

[英]TypeScript Error - Expected 1-2 arguments, but got 0 or more. TS2556

I was using this statement in JavaScript but when I try to use it in a TypeScript Project I get an error.我在 JavaScript 中使用了这个语句,但是当我尝试在 TypeScript 项目中使用它时出现错误。 It's complaining about the fetch(...args)它在抱怨 fetch(...args)

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

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

This should help you:这应该可以帮助您:

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

You should explicitly type arguments for fetch .您应该为fetch显式键入 arguments 。 It expects 1-2 arguments.它预计 1-2 arguments。

If you want to use rest operator, you should tell TS, that you also expect two arguments in your higher order function如果你想使用rest运算符,你应该告诉 TS,你也期望在你的高阶 function 中有两个 arguments

Taking this answer from comment by @Keith which was the only thing that worked for me:从@Keith 的评论中得到这个答案,这是唯一对我有用的东西:

const fetcher = (...args: Parameters<typeof fetch>) => {
  fetch(...args).then(response => response.json());
}

Specifically adding this Parameters<typeof fetch> as the type of ...args专门添加此Parameters<typeof fetch>作为...args的类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM