作者:手浪用户2602916293 | 来源:互联网 | 2023-09-15 12:27
我在 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
Not sure why @jcatz deleted his response, as `const fetcher = (...args: Parameters) => fetch(...args).then(respOnse=> response.json());` is a nice solution, as it lines up the parameters types automatically for you using Parameters & typeof.