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.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)