Description
TypeScript Version: [email protected]
Search Terms: union narrowing discriminate missing property field
Code
class Foo
{
private foo: string;
}
class Bar
{
private bar: number;
}
function fn(baz: { foo: Foo; bar: string; } | { foo: Bar; })
{
if (typeof baz.bar != 'undefined')
{
testFoo(baz.foo);
}
}
function testFoo(foo: Foo)
{
}
Expected behavior:
No Error. I can call testFoo(baz.foo)
since the union type is properly narrowed.
Actual behavior:
Property 'bar' does not exist on type 'Baz'.
Argument of type 'Foo | Bar' is not assignable to parameter of type 'Foo'.
Type 'Bar' is not assignable to type 'Foo'.
Property 'foo' is missing in type 'Bar'.
Related Issues: I've looked around but found none.
Although, in general, I do understand this should not work, I think it would help greatly if we had a way to discriminate on properties that are only in some of the members of a union.
One of the solutions could be to type properties, that are missing in some of the union members as prop?: void
, or prop?: never
, or prop?: undefined
, or whatever makes sense in the type system.