-
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
Improve type narrowing when working with generics #55060
Comments
But if you called it like this, your proposed narrowing would be invalidated: makePair<Enum>(Enum.A, { y: 3 }); |
Calling it appropriately narrows down the type correctly, however I also expected the narrowing to happen inside the if equality block in the function itself. Since this seems to be a long-standing issue, as well as a duplicate, feel free to close it. |
You're assuming function getAOrB() { return 0.5 > Math.random() ? Enum.A : Enum.B; }
const enumValue = getAOrB();
makePair(enumValue, { y: 3 }); // not a type error ...and there's no way, at the type level, to prevent that from happening. The lack of narrowing inside the function is therefore intentional--it wouldn't be sound to do so. Hence #27808 which would give you a way to explicitly tell the compiler that Footnotes
|
See also #30581 and related issues, which are fundamentally about a way to communicate to TS that |
I understand why this is the case for the function body in general, but I don't get how this is true within the strict equality branch. |
See my code example above. Having |
I get it - since I worked around the issue by casting Thank you for the explanations everyone! I'm going to close the ticket, since it seems like a duplicate to me. |
An object argument in a template function will have the members appropriately correlated -
but as you can see the extra args in the function call are not detected as errors. Using function overloads will detect the extra args in the function call -
|
Bug Report
π Search Terms
type narrowing, generics
π Version & Regression Information
β― Playground Link
https://www.typescriptlang.org/play?#code/KYOwrgtgBAou0G8BQUoEEoF4oEYA0KUAQllAExIC+SSALgJ4AOws8ACgIYCWATqcqgDacSADo0AXQBcUAaigAPGfABGwHgG5ClLYWHxRRabMKp6yyGs3at1JAGMA9iADOtKBA4BrYJ16kAHgAVKGAFWlAAExdWSAA+AAoAM143GSC8KBdgJxBImREIPx5BIIkASiw4k1QuJKhk1PdMFtiIcUq5VFyXRwAbYFE+xwBzBOzcyNEFcu0qJCA
π» Code
π Actual behavior
π Expected behavior
I expected typescript to narrow the type of T to the specific enum being used (due to the equality operator), and therefore the enum pair too.
The text was updated successfully, but these errors were encountered: