Suggestion: allow type predicates to be inferred when satisfies boolean
is present
#60778
Open
6 tasks done
Labels
Experience Enhancement
Noncontroversial enhancements
Help Wanted
You can do this
Suggestion
An idea for TypeScript
Milestone
π Search Terms
inferred type predicates, satisfies, return type
β Viability Checklist
β Suggestion
I would like to allow type predicates to be inferred when the returned value is constrained by a
satisfies boolean
expression.Concretely, I think this code should be legal:
π Motivating Example
I am a big fan of explicitly typing any and all function declarations. So, I would never omit the return type on a function like
However, with inferred type predicates, it's actually safer to omit the return type, since user-defined type predicates can be totally unsafe:
In other words, the safer code is
However, this is no longer visually explicit about what it's returning. And what's to stop future-me from making a typo and returning a non-boolean, completely changing the function's applicability.
Therefore, I'd like to be able to write
This is both visually clear and easily analyzable by tooling. For example, at typescript-eslint we'd like to implement typescript-eslint/typescript-eslint#9764, but without having an unresolvable conflict with explicit-function-return-type. Allowing a single-return
satisfies boolean
could be a good way to create a statically analyzable exception for explicit-function-return-type that also allows you to enforce writing boolean-returning functions that otherwise would be syntactically eligible for inferred type predicates to be written without the explicit return type. We have precedent for something similar being familiar to the community in typescript-eslint/typescript-eslint#10231, where asatisfies
expression is used to constrain but not change the return type of a function.π» Use Cases
: boolean
return type annotation if a predicate return type could be inferredΒ typescript-eslint/typescript-eslint#9764Note - an alternative, more general, approach could be to have a return type syntax like so:
This would indicate that the return type is constrained, but will still result in the more specific return type. This might also be useful in cases where a function is passed to a generic, or allowing a single
satisfies
constraint to apply to multiple return points, likeHowever, a) I don't think these are mutually exclusive, and b) the proposed solution does not require new syntax, whereas the alternate solution does.
The text was updated successfully, but these errors were encountered: