Hacker News new | ask | show | jobs
by mhink 1544 days ago
Yeah, they're called "type predicates" (or "type guards"). So you can do something like

    function isFish(pet: Fish | Bird): pet is Fish {
      return (pet as Fish).swim !== undefined;
    }
and Typescript is smart enough to let you use it in an if-branch

    // Both calls to 'swim' and 'fly' are now okay.
    let pet = getSmallPet();
 
    if (isFish(pet)) {
      pet.swim(); 
    } else {
      pet.fly();
    }
Typescript also has typechecker support for assertion functions. So like,

    function assertIsDefined<T>(val: T): asserts val is NonNullable<T> {
      if (val === undefined || val === null) {
        throw new AssertionError(`Expected 'val' to be defined, but received ${val}`);
      }
    }
Which we can use like so:

    function doSomething(pet: Fish | undefined) {
      assertIsDefined(pet);

      // safe to use without checking for null/undefined,
      // because our assertion function narrowed the type for 
      // usage later in the function 
      pet.swim();
    }