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
interfaceA{first: any;second: any;}interfaceB{second: any;}functionfunc(array: A[]|B[]){constitem=array[0];// typescript assumes item is of type 'B'if('first'initem){// typescript thinks this is impossiblereturnitem.first;}}
π Actual behavior
Typescript assumes that item is of type B.
Furthermore, when I try to narrow the type to A in order to access item.first, I get an error that says:
Property 'first' does not exist on type 'never'.(2339)
π Expected behavior
Typescript should infer that item is of type A | B, not B.
The error does not occur when A is not a supertype of B
Also, the error does not occur when array has type (A | B)[] instead of A[] | B[]. The problem is that sometimes the latter type is the implied by typescript when accessing the properties of union types. Consider the following example:
interfaceC{items: A[]}interfaceD{items: B[]}functionbar(value: C|D){constitem=value.items[0];// typescript assumes item is of type 'B'if('first'initem){// typescript thinks this is impossiblereturnitem.first;}}
The text was updated successfully, but these errors were encountered:
There isn't much we can do here; subtype reduction is necessary for many other things to work. You can declare A and B such that they are mutually exclusive if this is the case, otherwise a type assertion is appropriate here.
I understand if it's a design limitation but I don't know what you mean by "This is a widening, not a narrowing." In the example I gave, typescript assumes that item is of type B, which would be a narrowing no? (since it's a strict subset of the types that are actually possible, i.e. A OR B).
Also, I'm curious, what "other things" would not work if typescript inferred that item had type A | B instead of B?
Bug Report
β― Playground Link
Playground link
π» Code
π Actual behavior
Typescript assumes that
item
is of typeB
.Furthermore, when I try to narrow the type to
A
in order to accessitem.first
, I get an error that says:π Expected behavior
Typescript should infer that
item
is of typeA | B
, notB
.The error does not occur when
A
is not a supertype ofB
Also, the error does not occur when
array
has type(A | B)[]
instead ofA[] | B[]
. The problem is that sometimes the latter type is the implied by typescript when accessing the properties of union types. Consider the following example:The text was updated successfully, but these errors were encountered: