drunkdolphin
drunkdolphin

Reputation: 797

How to use spread syntax as arguments in function of TypeScript?

I wanted use array as function's arguments. So I used spread syntax as arguments like below.

const add = (x: number, y: number, z: number) => {
    return x + y + z
}
let array1 = [1,2,3];
console.log(add(...array1))

I ran my code, it didn't work and any arguments recognized in methods. I checked spread syntax correctly using by console.log(...array1) and then result is "1,2,3" as number. So why spread syntax wasn't recognized as arguments? Does anyone advise me?

Upvotes: 0

Views: 97

Answers (2)

zixiCat
zixiCat

Reputation: 1059

You can also const assertions, which makes array literals become readonly tuples.

const array1 = [1, 2, 3] as const;
array1.push(4); // error
// or
array1.pop(); // error

console.log(add(...array1));

By above way, you can make sure the length of array1

In following method, the length of array1 would be changed at any time and will show no error about it.

let array1: [number, number, number] = [1,2,3];
array1.push(4) // no error
// or
array1.pop() // no error

console.log(add(...array1))

Upvotes: 2

Silvio Mayolo
Silvio Mayolo

Reputation: 70387

Typescript tends to infer array types over tuple types if given the option. So if you want it to treat the array as a tuple, you have to say so.

let array1: [number, number, number] = [1,2,3];

Upvotes: 4

Related Questions