-
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
Arrow functions cannot be used as user-defined type guards #5951
Comments
Using a type assertion instead of type annotation does work var isReallyCat = <(a: Animal) => a is Cat>((cat) => cat.name === 'kitty'); so I imagine it's just an oversight rather than deliberate. |
The issue is that you don't want a function isHippopotamusFood(a: Animal): boolean {
// ...
}
let isReallyCat: (a: Animal) => a is Cat = isHippopotamusFood;
For that reason, type predicates need to be placed on the return type of the function proper. The declaration itself needs to opt in.
The following also works:
```ts
var isReallyCat: (a: Animal) => a is Cat = (cat): cat is Cat => cat.name === 'kitty'; or just var isReallyCat = (cat): cat is Cat => cat.name === 'kitty'; We could contextually type the return type to be a type predicate when appropriate, but I don't know if it'd really be worth it, and we usually never touch return types when performing contextual typing. |
Why not? Nothing prevents me from implementing a |
Sure, but you have to intentionally opt in to that, and if you're totally sure you want to sabotage your users' experiences, more power to you. We're trying to avoid people from accidentally assigning an arbitrary function to a type predicate. |
User defined type guards work perfectly well for classic function statements, as in the release notes:
However, it appears that the arrow function equivalent isn't acceptable:
This gives "Type '(cat: Animal) => boolean' is not assignable to type '(a: Animal) => a is Cat'. Signature '(cat: Animal): boolean' must have a type predicate". I'm not clear how I would give that arrow function a 'type predicate', beyond what's already included here.
Is there a good reason for this? I can't seem to find it documented anywhere.
The text was updated successfully, but these errors were encountered: