Home > Enterprise >  Spread Operator - TypeScript
Spread Operator - TypeScript

Time:04-02

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)

CodePudding user response:

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)
}

CodePudding user response:

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];
  • Related