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
If we have a union type array like declare const array: string[] | number[], and the first element type is determined in a branch, we should be able to narrow the array type to string[] or number[].
(Of course we can now use custom type guards for our purposes, but it would be exciting if this were all automated.)
// ts version: 4.6.4// case 1declareconstarray: string[]|number[]functiondoSomething(){if(typeofarray[0]==='string'){constfirstElement=array[0]// When the mouse hovers over the variable, you can see that the ts engine correctly infers the type, which is 'string'typefirstElementType=typeofarray[0]// should be 'string' (currently it is 'string | number')typearrayType=typeofarray// should be 'string[]' (currently it is 'string[] | number[]')}}// case 2interfaceA{foo: number}interfaceB{bar: number}declareconstarray2: A[]|B[]functiondoSomething2(){if('foo'inarray2[0]){constfirstElement=array2[0]// When the mouse hovers over the variable, you can see that the ts engine correctly infers the type, which is 'A'typefirstElementType=typeofarray2[0]// should be 'A' (currently it is 'A | B')typearrayType=typeofarray2// should be 'A[]' (currently it is 'A[] | B[]')}}// No longer need to write a custom type guard as a helper function like this:functionboringButNeededHelperGuard(array: string[]|number[]): array is string[]{returntypeofarray[0]==='string'}
π» Use Cases
Save time writing custom type guards, and code reading experience will be better
The text was updated successfully, but these errors were encountered:
Suggestion
π Search Terms
is:issue union type array guard first element
β Viability Checklist
My suggestion meets these guidelines:
β Suggestion
If we have a union type array like
declare const array: string[] | number[]
, and the first element type is determined in a branch, we should be able to narrow the array type tostring[]
ornumber[]
.(Of course we can now use custom type guards for our purposes, but it would be exciting if this were all automated.)
π Motivating Example
playground
π» Use Cases
Save time writing custom type guards, and code reading experience will be better
The text was updated successfully, but these errors were encountered: