TypeScript 的 type predicates
生活随笔
收集整理的這篇文章主要介紹了
TypeScript 的 type predicates
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
TypeScript type predicates 實際上是一種用戶定義的 type guard 的實現方式。
要定義用戶定義的類型保護,我們只需要定義一個返回類型為類型謂詞 (type predicates) 的函數:
function isFish(pet: Fish | Bird): pet is Fish {return (pet as Fish).swim !== undefined;}在這個例子中,pet is Fish 是我們的類型謂詞。 謂詞采用 parameterName is Type 形式,其中 parameterName 必須是當前函數簽名中的參數名稱。
例子:
type Fish = { swim: () => void };type Bird = { fly: () => void };function isFish(pet: Fish | Bird): pet is Fish {return (pet as Fish).swim !== undefined;}function getSmallPet(index:number){if( index === 1){return {swim: () => console.log('Hello')}}return {fly: () => console.log('!')}}let pet = getSmallPet(1);if (isFish(pet)) {pet.swim();} else {pet.fly();}總結
以上是生活随笔為你收集整理的TypeScript 的 type predicates的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 抖音310是什么意思 抖音310来源详情
- 下一篇: TypeScript 里 never 类