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



Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 CertainPerformance