[英]Spread Operator - TypeScript
It's exactly as the error says:就像错误所说的那样:
A spread argument must either have a tuple type or be passed to a rest parameter.传播参数必须具有元组类型或传递给 rest 参数。
So either make args
a tuple, such as with as const
so it doesn't get widened to number[]
:所以要么使args
成为一个元组,例如 with as const
这样它就不会扩大到number[]
:
const args = [2, 6, 4] as const;
Or make the parameters a rest parameter instead:或者将参数改为 rest 参数:
function addThreeNumbers(...args: number[]) {
console.log(args[0] + args[1] + args[2])
// or args.reduce((a, b) => a + b, 0)
}
For TypeScript to correctly predict what argument types are going to spread into the parameter, you will have to change the args
variable type into a tuple as follows:为了 TypeScript 正确预测哪些参数类型将传播到参数中,您必须将args
变量类型更改为元组,如下所示:
const args: [number, number, number] = [2, 6, 4];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.