Description
Suggestion
π Search Terms
type
narrowing
array
β Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- It's a matter of accurately inferring types, it would only make code less verbose by requiring fewer type assertions.
- This wouldn't change the runtime behavior of existing JavaScript code
- Purely a typing issue
- This could be implemented without emitting different JS based on the types of the expressions
- This only makes it easier to appease the typechecker
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- It's a compile-time change
- This feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
Currently, it is not possible to narrow down the type of a union of arrays based on the types of their contents, even if the arrays of the union are disjunct. I suggest updating the typechecker, if possible, to allow for this.
π Motivating Example
If we try to do it the naive way, we get the following scenario:
function fun1(array: number[] | string[]) {
if (array.length > 0 && typeof array[0] === "number") {
array // Actual type: number[] | string[]
// Desired type: number[]
}
}
function fun2(array: [number, ...number[]] | [string, ...string[]]) {
if (typeof array[0] === "number") {
array // Actual type: [number, ...number[]] | [string, ...string[]]
// Desired type: [number, ...number[]]
}
}
Instead, the programmer is forced to write a type assertion on top of verifying the type of the array
function fun1(array: number[] | string[]) {
if (array.length > 0 && typeof array[0] === "number") {
array as number[]
}
}
function fun2(array: [number, ...number[]] | [string, ...string[]]) {
if (typeof array[0] === "number") {
array as [number, ...number[]]
}
}
This is not ideal, as it makes for needlessly verbose code. There's also no simple way to implement a type predicate to do this generically over any array of any type.
The ideal scenario would be for the first example to infer the desired types.
π» Use Cases
This makes for cleaner code and a more streamlined and intuitive user experience. The current approach makes for clunky and bloated code when dealing with arrays, as the only way to properly type things is with type assertions.