Skip to content
Advertisement

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)

Advertisement

Answer

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