简体   繁体   English

传播运营商 - TypeScript

[英]Spread Operator - TypeScript

I'm trying to pass an array as an argument with Spread operator but something is going wrong.我正在尝试将数组作为参数传递给 Spread 运算符,但出了点问题。

function addThreeNumbers(x:number, y:number, z:number){
  console.log(x+y+z)
}

const args: number[] = [2,6,4]

addThreeNumbers(...args)

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.

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