![](/img/trans.png)
[英]TypeScript Error - Expected 1-2 arguments, but got 0 or more. TS2556
[英]Spreading an array in a typescript function: Error TS2556
我正在尝试在这样的打字稿函数调用中使用传播运算符:
function foo(x: number, y: number, z: number) {
console.log(x + y + z);
}
const args = [0, 1, 2];
foo(...args);
但是在编译时,我收到错误:“传播参数必须具有元组类型或传递给 rest 参数”(TS2556)。 我究竟做错了什么?
附录:当我的参数是一个动态数组时,我该如何解决这个问题,如
const args = new Array(3).map(() => Math.random());
编辑动态生成的args
:
选项一:如果您确定args
将始终是 3 个元素的元组,请使用类型断言。
const args = new Array(3).map(() => Math.random()) as [number, number, number];
选项二,定义foo
接受 rest 参数:
function foo(...args: number[]) {
console.log(args[0] + args[1] + args[2]);
}
const args = new Array(3).map(() => Math.random());
foo(...args);
预定义args
的旧答案
您可以将 args 断言为 const:
const args = [0, 1, 2] as const;
或者按照错误提示将 args 定义为元组:
const args: [number, number, number] = [0, 1, 2];
这是为了保证args
中元素的数量/类型始终与函数参数的要求相匹配。
参数不能以这种方式工作,这就是你应该如何使用它们 args
function multiply(n, ...m) {
return m.map((x) => n * x);
}
// 'a' gets value [10, 20, 30, 40]
const a = multiply(10, 1, 2, 3, 4);
您可以使用const 断言来解决这个问题。 因为函数foo
需要 3 个参数:
function foo(x: number, y: number, z: number) {
console.log(x + y + z);
}
const args = [0, 1, 2] as const;
foo(...args);
对于动态推断的参数大小, as const
方法不起作用。
另一种解决方案是在.apply()
调用中使用...args
生成的数组。 Typescript 对此没有抱怨:
export class CustomError<
ErrorCode extends keyof typeof CustomError.codes,
ErrorParams extends Parameters<typeof CustomError.codes[ErrorCode]>
> extends Error {
constructor(public code: ErrorCode, ...args: ErrorParams) {
super(CustomError.codes[code].apply(null, args))
}
static codes = {
invalidEmail (email: string) {
return `Email ${email} is invalid`
},
invalidPasswordConfirm: (a: string, b: string) {
return `Password ${a} and confirm ${b} are different`
}
}
}
new CustomError('invalidEmail', 'aaa@bbb')
// ^ CustomError(code: "invalidEmail", email: string)
new CustomError('invalidPasswordConfirm', 'first', 'second')
// ^ CustomError(code: "invalidPasswordConfirm", a: string, b: string)
遭受A spread argument must either have a tuple type or be passed to a rest parameter.
,您可能需要检查您的 devDependencies 中是否安装了 typescript typescript-parser
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.