-
-
Notifications
You must be signed in to change notification settings - Fork 549
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
Proposal: Predicate inferer #973
Comments
Sounds useful, but the name is slightly confusing. The type extracts the inferred guard type, but a name like |
I agree |
This type would be similar to |
Looks interesting, are there any use cases? |
@Emiyaaaaa rather than having to rely on manually maintaining consistency across explicit predicates and implementations, it allows to derive types from guard function implementations, the latter being less error-prone. For example: // Before
type Valid = string | number | null // Let's say a dev decided to add null to this union.
// When declared explicitly, the predicate can diverge from the actual implementation if not cautious.
function isValid(value: string | number | null | undefined | false): value is Valid {
return value != null && value !== false;
} // After
function isValid(value: string | number | null | undefined | false) {
return value != null && value !== false;
}
type Valid = Predicate<typeof isValid> // This will always be up to date with the guard implementation. Use cases include typing function params based on guard implementations or extracting type from data parsing functions without having to explicitly repeat types now adequately inferred by ts. |
Type description + examples
With typescript now supporting predicate inference for guard functions without the need for explicitly specifying a
is
clause, it could be interesting to provide a simple helper that allows to get the inferred predicate for any guard function.Ex.:
Type source
Search existing types and issues first
Upvote & Fund
The text was updated successfully, but these errors were encountered: