TS 類型收窄教程示例詳解
類型收窄之前只能使用公共方法
JS方法
typeof
缺點(diǎn)
- typeof null —→ object
- typeof 數(shù)組 —→ object
- typeof 日期 —→ object
a instanceof A : A 是否出現(xiàn)在a的原型鏈上
缺點(diǎn)
不支持string
、number
、boolean
等原始類型
不支持TS的 自定義類型,如下:
type Person { name: string }
- key in obj
- Array.isArray()
????類型謂詞is
重點(diǎn)在 shape is Rect
type Rect = { width: number height: number } type Circle = { center: [number, number] radius: number } const area = (shape: Rect | Circle): number => { if(isRect(shape)) { return shape.width * shape.height } else { return Math.PI * shape.radius ^ 2 } } const isRect = (shape: Rect | Circle): shape is Rect => { return 'width' in shape && 'height' in shape }
????????可辨別聯(lián)合
要求:T = A | B | C
- A | B | C … 要有一個(gè)相同的屬性 type或其它
- type類型只能為 簡(jiǎn)單類型
- A | B | C …的type屬性無(wú)交集
type Rect = { type: 'rect', width: number height: number } type Circle = { type: 'circle' center: [number, number] radius: number } const area = (shape: Rect | Circle): number => { if(shape.type === 'rect') { return shape.width * shape.height } else { return Math.PI * shape.radius ^ 2 } }
以上就是TS 類型收窄教程示例詳解的詳細(xì)內(nèi)容,更多關(guān)于TS 類型收窄的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
定時(shí)器在頁(yè)面最小化時(shí)不執(zhí)行實(shí)現(xiàn)示例
這篇文章主要為大家介紹了定時(shí)器在頁(yè)面最小化時(shí)不執(zhí)行的實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07詳解微信小程序Page中data數(shù)據(jù)操作和函數(shù)調(diào)用
這篇文章主要介紹了詳解微信小程序Page中data數(shù)據(jù)操作和函數(shù)調(diào)用的相關(guān)資料,希望通過(guò)本文能幫助到大家掌握這方法,需要的朋友可以參考下2017-09-09Vue.js React與Angular流行前端框架優(yōu)勢(shì)對(duì)比
這篇文章主要為大家介紹了Vue.js React與Angular流行前端框架優(yōu)勢(shì)對(duì)比,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03ChatGPT前端編程秀之別拿編程語(yǔ)言不當(dāng)語(yǔ)言
這篇文章主要為大家介紹了ChatGPT前端編程秀之教你別拿編程語(yǔ)言不當(dāng)語(yǔ)言,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03Servlet3.0與純javascript通過(guò)Ajax交互的實(shí)例詳解
Servlet與純javascript通過(guò)Ajax交互,對(duì)于很多人來(lái)說(shuō)應(yīng)該很簡(jiǎn)單。不過(guò)還是寫(xiě)寫(xiě),方便Ajax學(xué)習(xí)的后來(lái)者2018-03-03