The typescript handbook on user defined type guards defines an example type guard as
function isFish(pet: Fish | Bird): pet is Fish {
return (<Fish>pet).swim !== undefined;
}
Is there a corresponding syntax for arrow functions?
TypeScript supports arrow-function type guards (which may have not been the case in 2017). The following now works as expected. I've used this style frequently in production code:
const isFish = (pet: Fish | Bird): pet is Fish =>
(pet as Fish).swim !== undefined;
Yes, just as you would have returned boolean
, you simply return pet is Fish
:
const isFish: (pet: Fish | Bird) => pet is Fish = pet => (pet as Fish).swim !== undefined
Arrow functions are declared as a single type ((pet: Fish | Bird) => pet is Fish
) rather than the parameters and the return type separately.
Use type assertion instead of type declaration:
const isFish = (pet => !!pet.swim) as (pet) => pet is Fish
However, given the fact that it is more verbose, I would prefer to write type guards as normal functions, unless you really need the this
binding, but that is probably a code smell.
as an alternative, this also works
const isFish = (pet: any): pet is Fish => !!pet.swim;
or if you prefer to be more explicit
const isFish = (pet: any): pet is Fish => pet.swim === 'function';
while the test can be made against properties as well
const isFish = (pet: any): pet is Fish => pet.hasOwnProperty('genus');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With