Description
(Apologies if this is a duplicate; I suspect that it is after seeing so many related questions being marked "behaving as designed," but am having a hard time figuring out exactly which issue this may be duplicating).
TypeScript Version: 2.8.3
Search Terms: discriminated union, conditional generic, etc...
Code
interface Foo {
hasADate: true;
obj: Date;
}
interface Bar {
hasADate: false;
obj: number;
}
type FooBar = Foo | Bar;
type GenericFooBar<T> = T extends Function ? Foo : Bar;
function testing<T>(doesntWork: GenericFooBar<T>) {
if (doesntWork.hasADate === true) {
return doesntWork.obj.getDate(); // ERROR: arg.obj is still type number | Date
}
let works: FooBar = doesntWork;
if (works.hasADate === true) {
return works.obj.getDate(); // WORKS: arg.obj is type Date
}
}
Expected behavior:
Inside of the doesntWork.hasADate === true
type guard, doesntWork.obj
should be narrowed to a Date
Actual behavior:
doesntWork.obj
is still a number | Date
. The compiler does allow me to assign doesntWork
to works
(whose type is the respective discriminated union), and with that variable everything works as expected. It seems odd that the compiler recognizes that GenericFooBar<T>
extends Foo | Bar
(as it allows the assignment), yet doesn't work with the discriminated type guard.