Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type inference when using array destructuring assignment fails to catch undefined values when the array is shorter than the destructure expression #46026

Closed
mturley opened this issue Sep 23, 2021 · 2 comments

Comments

@mturley
Copy link

mturley commented Sep 23, 2021

Bug Report

πŸ”Ž Search Terms

array destructure assignment inference rest undefined
(found semi-related #21519)

πŸ•— Version & Regression Information

Found in version 4.0.0, reproduced in nightly

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

const arr: number[] = [];

// foo and bar are both inferred to be of type number, but they should be (number | undefined).
const [foo, bar] = arr;

// Same here, baz is a number but should be (number | undefined). rest is correctly inferred as number[].
const [baz, ...rest] = arr;

console.log({ foo, bar, baz, rest }); // foo, bar and baz are undefined (!)

const add = (a: number, b: number) => a + b;

// This should be an error like "Argument of type 'undefined | number' is not assignable to parameter of type 'number'".
// Instead it compiles with sum inferred to be a number, but in fact it is NaN.
const sum = add(foo, 2);
console.log(sum);

πŸ™ Actual behavior

When destructuring an array, if the number of declared variables is longer than the length of the array, the extra ones will be undefined. However, TypeScript always infers the type of these variables to be defined. This can lead to uncaught errors when destructuring arrays that can be empty. Passing these destructured values to functions that require defined parameters will cause errors at run time that the compiler could easily catch.

πŸ™‚ Expected behavior

I would expect the inferred type of these destructured variables to be T | undefined where the type of the array is T[].

@mturley mturley changed the title Type inference when using array destructuring assignment fails to catch undefined values Type inference when using array destructuring assignment fails to catch undefined values when the array is shorter than the destructure expression Sep 23, 2021
@MartinJohns
Copy link
Contributor

This is working as intended. When you enable noUncheckedIndexedAccess you get number | undefined.

@mturley
Copy link
Author

mturley commented Sep 23, 2021

Ah! Oops, thanks.

@mturley mturley closed this as completed Sep 23, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants