Search code examples
typescript

Why does TypeScript not allow passing an array with the spread operator as function parameters?


This is how the JavaScript spread operator allows passing an array as function arguments:

function f(a, b) { console.log(a, b) }
let arr = [1, 2]
f(...arr) // all fine!

TypeScript 5.3.2 does not accept this, however:

function f(a, b) { console.log(a, b) }
let arr = [1, 2]
f(...arr) // error: A spread argument must either have a tuple type or be passed to a rest parameter.(2556)

Playground

To me this is a bug, because valid JavaScript should always be valid TypeScript.

How can I circumvent this error, why does it occur?

Found a long discussion in the TypeScript repo: microsoft/TypeScript#49700.


Solution

  • The problem here is that the default inferred type for arr is number[], so a normal array with unspecified length.

    If you explicitly specify arr to be a tuple (compatible with the function signature), e.g. [number, number], it works correctly. E.g.:

    function f(a: unknown, b: unknown) { console.log(a, b) }
    let arr: [unknown, unknown] = [1, 2]
    f(...arr)