DEV Community

Wes
Wes

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

1

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)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay