You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
constarr: 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 (!)constadd=(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.constsum=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[].
The text was updated successfully, but these errors were encountered:
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
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
π 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 isT[]
.The text was updated successfully, but these errors were encountered: