You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Arrow functions cannot be used as user-defined type guards #5951
User defined type guards work perfectly well for classic function statements, as in the release notes:
interfaceAnimal{name: string;}interfaceCatextendsAnimal{meow();}functionisCat(a: Animal): a is Cat{returna.name==='kitty';}
However, it appears that the arrow function equivalent isn't acceptable:
// Doesn't compilevarisReallyCat: (a: Animal)=>a is Cat=(cat)=>cat.name==='kitty';
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 issue is that you don't want a boolean-returning function to be assignable to a type-guard.
functionisHippopotamusFood(a: Animal): boolean{// ...}letisReallyCat: (a: Animal)=>a is Cat=isHippopotamusFood;Forthatreason,typepredicatesneedtobeplacedonthereturntypeofthefunctionproper.Thedeclarationitselfneedstooptin.Thefollowingalsoworks:
```tsvarisReallyCat: (a: Animal)=>a is Cat=(cat): cat is Cat=>cat.name==='kitty';
or just
varisReallyCat=(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.
Reacted by Gábor IMRE and Konstantins Starovoitovs
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.
Activity
Arnavion commentedon Dec 6, 2015
Using a type assertion instead of type annotation does work
so I imagine it's just an oversight rather than deliberate.
DanielRosenwasser commentedon Dec 6, 2015
The issue is that you don't want a
boolean-returning function to be assignable to a type-guard.or just
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.
Arnavion commentedon Dec 6, 2015
Why not? Nothing prevents me from implementing a
x is Foofunction withMath.random()either.DanielRosenwasser commentedon Dec 6, 2015
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.