`undefined` not inferred when destructuring an empty typed array
iagoqo opened this issue · 8 comments
TypeScript Version: 3.8.3
Search Terms:
array destructuring, destructuring, empty array, undefined
Expected behavior:
When destructuring an empty typed array to get a single item the resulting values should include undefined as a possible type.
Array.prototype.shift() includes undefined as a possible return type, the behaviour should be similar when destructuring.
Actual behavior:
The destructured values are inferred to only be of the same type as the array.
Related Issues:
No
Code
const myArray: string[] = [];
// type: string, should be string | undefined
const [firstItem] = myArray;
//type: string, should be string | undefined
const myItem = myArray[10];Output
"use strict";
const myArray = [];
// type: string, should be string | undefined
const [firstItem] = myArray;
//type: string, should be string | undefined
const myItem = myArray[10];Compiler Options
{
"compilerOptions": {
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"strictBindCallApply": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"useDefineForClassFields": false,
"alwaysStrict": true,
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"downlevelIteration": false,
"noEmitHelpers": false,
"noLib": false,
"noStrictGenericChecks": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"esModuleInterop": true,
"preserveConstEnums": false,
"removeComments": false,
"skipLibCheck": false,
"checkJs": false,
"allowJs": false,
"declaration": true,
"experimentalDecorators": false,
"emitDecoratorMetadata": false,
"target": "ES2017",
"module": "ESNext"
}
}Playground Link: Provided
I am not sure if this should be marked as a duplicate to #13778. I think this issue needs to be separated. Right now Array Destructuring is providing inaccurate types. That issue has gotten away from that topic entirely to create a complex decision on how to handle types inside loop functions. #36635 (comment)
There's no way we would change this behavior without #13778 or vice versa, so it's a duplicate
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.
Please re-open this. It's not resolved :) Here's an example of the problem in version 4.3.5.
I basically have to think for typescript when destructing arrays of objects that might be empty, which TypeScript basically taught me to look out for, but it would be nice if it did as it usually does.
It is resolved; you have to use --noUncheckedIndexedAccess. [Playground]
Alright, thanks. I guess I had expected this check to be opt out, not opt in.
Same, but now i read the reason #42016 (comment) which makes sense. Also with this flag on it gives so many side effects on things my editor has no problem with inferring it correctly. I just saw the problem with empty arrays :(