Created
October 10, 2020 18:31
-
-
Save wes-goulet/f176ded80a4e0b9130476a75efbcb06e to your computer and use it in GitHub Desktop.
Type Guard in jsdoc comment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @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