gamliela
gamliela

Reputation: 4069

Array destructuring is not working with parameters to a function

I'm learning TypeScript so please accept my apologies for asking a dumb question.

The following code is taken from the official docs, but it is not working. It looks like the function is expecting a Tuple of two numbers instead of Array, but on the other hand it should demonstrate Array destructuring according to the docs...

let input = [1, 2];
function f([first, second]: [number, number]) {
    console.log(first);
    console.log(second);
}
f(input);

The error:

src/main.ts(6,3): error TS2345: Argument of type 'number[]' is not assignable to parameter of type '[number, number]'.
  Property '0' is missing in type 'number[]'.

Upvotes: 1

Views: 619

Answers (2)

MoMo
MoMo

Reputation: 1876

@gamliela, to add a variation to @artem 's response, it's best to properly define the tuple type in first place:

let input:[number,number] = [1, 2];
let [first, second] = input;

As such the TS2345 warning for:

f(input)

will disappear.

Note, if you copy the doc example as-is to the playground, it shows the same TS2345 warning unless you add the proper tuple type definitions above.

Upvotes: 0

artem
artem

Reputation: 51629

It looks like the example is indeed wrong or obsolete, or maybe it's a bug in typescript compiler. You are right, [number, number] is a tuple type, and the type of input is inferred to be number[], that is, the length of array is not preserved in the type, and you get error message because f expects an array of exactly 2 elements.

If you call f with literal array it will work

f([1, 2]); // ok

You can also make it work if you declare argument as array:

let input: number[] = [1, 2];
function f([first, second]: number[]) {
    console.log(first);
    console.log(second);
}

f(input);

but it will not be checking array length that way, these calls would compile too:

f([]);
f([1, 2, 3]);

Upvotes: 3

Related Questions