JSDocコメントを使用したJavaScriptのタイプガード
4021 ワード
タイプスクリプトでは、単一のタイプにユニオン型をフィルタダウンするためにtype guardsを書くことができます.例えば、
タイプのチェック
JavaScriptであなたのコードを書いて、JSDoc comments for type-checking and intellisenseを使うならば?あなたはまだ書くことができるタイプガードを使用する!
// 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();
}
タイプのチェック
JavaScriptであなたのコードを書いて、JSDoc comments for type-checking and intellisenseを使うならば?あなたはまだ書くことができるタイプガードを使用する!
/** @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();
}
Hopefully you found this post helpful, if you have any questions you can find me .
Reference
この問題について(JSDocコメントを使用したJavaScriptのタイプガード), 我々は、より多くの情報をここで見つけました https://dev.to/wes_goulet/type-guards-in-javascript-using-jsdoc-comments-36l2テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol