-
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
narrowing in switches doesnt work on constrained unions #20375
Comments
Nvm earlier comment, misunderstood what you meant by "extended". The weird part here is |
Generics that are constrained to literal types are not treated like literals at the moment. generics have a more conservative behavior when narrowing in general since the actual type is not known, but generics with literal constraints should be behave like a union of literals. |
In the first example, declare var n: never;
function fn<Y extends "A" | "B" | "C">(y: Y): Y {
switch (y) {
case 'A': n = y; return y; // ok!
case 'B': n = y; return y;
case 'C': n = y; return y;
default: n = y; return never(y); // <-- y expected to be never, actual Y
}
} |
This is indeed super wrong |
Upon thinking about it some more (and fixing the bug), I don't think this is actually super wrong. It's correct in an annoying way. Consider the non-type-parameter example, which the compiler correctly complains about: function f(ab: 'a' | 'b') {
switch(ab) {
case 'a': return ab;
case 'b': return ab;
case 'c': return ab;
default: return ab;
}
}
However, this is useless and annoying because even though |
what you say is indeed true in a non-practical way, yes one cannot narrow an unknown something like we know what it is, but here instead we are narrowing in assumption that we cover all possible cases out there, so i guess it's still correct |
The fact that type narrowing does not work as expected in conjunction with generic constraints is very subtle and confusing behavior. I've been trying to figure out why we haven't been able to get this to work in our codebase for quite a while, thinking it was an issue with our interface definitions, before finally stumbling across this issue. We use |
Is this different from #13995? |
This issue is now fixed in #43183. |
assuming my understanding it right: an extended union is a subset (subtype) of the original union
same problem with objects
The text was updated successfully, but these errors were encountered: