DEV Community

loading...

Type Guards in Javascript Using JSDoc Comments

Wes
Software developer, trying to build/learn all the stacks. Fan of PWAs and WebComponents. Simple/boring code FTW!
Originally published at goulet.dev ・1 min read

In Typescript you can write type guards to filter down a union type to a single type. For example:

// user-defined type guard
function isFish(pet: Fish | Bird): pet is Fish {
  return "swim" in pet;
}

const pet: Fish | Bird = getPet();

// at this point you either have a Fish or Bird

if(isFish(pet)) {
    // at this point you (and tsc and intellisense) know you have a Fish
    pet.swim();
} else {
    // at this point you (and tsc and intellisense) know you have a Bird
    pet.fly();
}

JSDoc Type-Checking Version

What if you write your code in Javascript and use JSDoc comments for type-checking and intellisense? You can still write and use type guards!

/** @typedef {{swim: () => void}} Fish */
/** @typedef {{fly: () => void}} Bird */

/**
 * @param {Fish | Bird} pet
 * @returns {pet is Fish}
 */
function isFish(pet) {
  return "swim" in pet;
}

/** @type {Fish | Bird} */
let pet = getPet();

// at this point "pet" is either a Fish or Bird

if (isFish(pet)) {
  // at this point you (and tsc and intellisense) know you have a Fish
  pet.swim();
} else {
  // at this point you (and tsc and intellisense) know you have a Bird
  pet.fly();
}

Hopefully you found this post helpful, if you have any questions you can find me on Twitter.

Discussion (0)