Search code examples
typescripttypesarrow-functions

Arrow style user defined type guard?


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?


Solution

  • 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;