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.
Activity
mhegazy commentedon May 8, 2018
This is no different from:
The underlying issue here is narrowing does not work on higher order types. what we need here is to first enable narrowing to work on
T
and in the true branch to beT extends Foo
and in the false branchT extends Bar
.#22348 is the start of this change.
ahejlsberg commentedon May 8, 2018
Adding to what @mhegazy just said... Typically, conditional types are useful in return types where they can depend on type parameters that in turn are used in parameter types such that inferences can be made for them. As you have it written in your example, we can't make any inferences for
T
and therefore you'd have to always specify it manually--which sort of defeats the purpose.DavidKDeutsch commentedon May 9, 2018
@mhegazy, thanks for that code snippet; I was so sure this had to do with conditional types that I never thought to try a simpler case like that one.
KSXGitHub commentedon May 15, 2018
@DavidKDeutsch Why did you closed this issue? I think this is a good suggestion.
DavidKDeutsch commentedon May 16, 2018
@KSXGitHub I closed it because I had not realized that my particular problem really didn't have anything to do with the new conditional type functionality; it's a pre-existing issue with generics in general (as @mhegazy demonstrated for me), and is already being worked on in #22348. I didn't want to clutter the open issues list with a duplicate (I figured it was a duplicate of something when I first posted it, but didn't know what that "something" was).
That being said, if @mhegazy thinks it is a useful ticket to keep open, he or I can reopen it. I'm just trying to be a good citizen :)