Array Destructuring Inference Is Incorrect
Skillz4Killz opened this issue · 3 comments
Search Terms
array destructuring, array destructuring inference
Suggestion
When you use array destructuring the type is inferred incorrectly. I hope something can be changed to enforce proper type inference when using this. In my code, TS has helped clean and prevent a lot of mistakes. The only mistakes that I repeatedly find being made either by me or others in my project are always related to this. Time and time again I have had these errors happen in runtime making the benefits of Typescript lost. An option to enforce this would be amazing, please. (Especially if it is just included inside the strict
option.)
Use Cases
const example = (args: string[]) => {
const [userID, duration, ...reason] = args
// userID and duration is AUTOMATICALLy inferred to be a string here.
// However, if for whatever reason args is an empty array userID is actually `undefined` and NOT a `string`.
// This is valid but it should not be because userID could be undefined
userID.toUpperCase()
}
Examples
const example = (args: string[]) => {
const [userID] = args
// userID is AUTOMATICALLy inferred to be a string here.
// However, if for whatever reason args is an empty array userID is actually `undefined` and NOT a `string`.
// Typescript SHOULD warn that this is not possible on undefined
userID.toUpperCase()
}
Proper Way:
const example = (args: string[]) => {
const [userID, duration, ...reason] = args
if (!userID) return
// This is valid but it should not be because userID could be undefined
userID.toUpperCase()
}
Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
We'd do this at the same time as #13778, so marking as duplicate
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.
@RyanCavanaugh Is it possible to re-open this issue and consider it separate from #13778 ?
I believe 13778 has gone off to a side where the issue with array destructuring having inaccurate types may be getting delayed to be fixed because of other users wanting to try and have this in loops as well(which i disagree with). I think the behavior in loops, .map and such are fine as is. Array destructuring is the issue imo.
I just prevented this issue in a deployment that would have basically broken about 50% of my project only because I was aware of this bug. Could have potentially effected a ton of users.