1

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[]'.

2 Answers 2

3

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

Comments

0

@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.

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.