简体   繁体   中英

Spread Operator - TypeScript

I'm trying to pass an array as an argument with Spread operator but something is going wrong.

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.

So either make args a tuple, such as with as const so it doesn't get widened to number[] :

const args = [2, 6, 4] as const;

Or make the parameters a rest parameter instead:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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