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();
}

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  Fish */
/** @typedef 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.

iOS 14 PWA Improvements
Detect if a PWA is Visible with the Page Visibility API