0

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?

2 Answers 2

4

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];
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your comment! I really appreciate it!
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.