Skip to content

Instantly share code, notes, and snippets.

@wes-goulet
Created October 10, 2020 18:31
Show Gist options
  • Save wes-goulet/f176ded80a4e0b9130476a75efbcb06e to your computer and use it in GitHub Desktop.
Save wes-goulet/f176ded80a4e0b9130476a75efbcb06e to your computer and use it in GitHub Desktop.
Type Guard in jsdoc comment
/** @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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment