-
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
Infer type guard from predicate for functions accepting type guards. #19468
Comments
Duplicate of #10734 and #14891 and #5101 (with a relevant comment) |
Thanks for finding that @jcalz |
To clarify, I'm looking for a general solution that doesn't require explicit definition of the narrowed guard type, not just an overload to |
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
1 similar comment
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed. |
It would be great to avoid the ceremony of having to declare separate type guards for functions accepting a type guard as an argument.
Consider functions like
Array.filter
orObservable.filter
being used to filter a union type with discriminant:However this is quite a lot of wiring for something that anywhere else is quite straight forward. In an if/else or switch block, a type guard isn't necessary... Typescript infers the type from the predicate:
Having to declare the type guard also requires us to 'repeat' out the shape of the type which can be quite painful if it isn't a type alias or class... i.e. we have to explicitly write `fb is { type: 'foo' }.
Typescript should be able to infer that the correct type is
{ type: 'foo' }
from the supplied predicate.In such an ideal world, we should be able to simply write:
If Typescript requires us to explicitly opt-in the function as a type-guard, then it should be possible to do so without explicitly repeating the type in the declaration. Maybe something like:
The text was updated successfully, but these errors were encountered: