DEV Community

Wes
Wes

Posted on • Updated on • Originally published at goulet.dev

Type Guards in Javascript Using JSDoc Comments

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();
}
Enter fullscreen mode Exit fullscreen mode

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();
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)