-
Notifications
You must be signed in to change notification settings - Fork 12.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conditional Type is assignable to a discriminated union, yet not working with type guards as expected. #23985
Comments
This is no different from: function testing<T extends Foo | Bar>(doesntWork: T){
if (doesntWork.hasADate === true) {
return doesntWork.obj.getDate(); // ERROR: arg.obj is still type number | Date
}
} 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 #22348 is the start of this change. |
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 |
@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. |
@DavidKDeutsch Why did you closed this issue? I think this is a good suggestion. |
@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 :) |
(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
Expected behavior:
Inside of the
doesntWork.hasADate === true
type guard,doesntWork.obj
should be narrowed to aDate
Actual behavior:
doesntWork.obj
is still anumber | Date
. The compiler does allow me to assigndoesntWork
toworks
(whose type is the respective discriminated union), and with that variable everything works as expected. It seems odd that the compiler recognizes thatGenericFooBar<T>
extendsFoo | Bar
(as it allows the assignment), yet doesn't work with the discriminated type guard.The text was updated successfully, but these errors were encountered: