TS 類型收窄教程示例詳解
更新時間:2022年09月20日 14:20:34 作者:dingsheng
這篇文章主要為大家介紹了TS 類型收窄教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
類型收窄之前只能使用公共方法
JS方法
typeof
缺點
- typeof null —→ object
- typeof 數(shù)組 —→ object
- typeof 日期 —→ object
a instanceof A : A 是否出現(xiàn)在a的原型鏈上
缺點
不支持string 、number 、boolean 等原始類型
不支持TS的 自定義類型,如下:
type Person {
name: string
}
- key in obj
- Array.isArray()
????類型謂詞is
重點在 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 … 要有一個相同的屬性 type或其它
- type類型只能為 簡單類型
- A | B | C …的type屬性無交集
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 類型收窄的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳解微信小程序Page中data數(shù)據(jù)操作和函數(shù)調(diào)用
這篇文章主要介紹了詳解微信小程序Page中data數(shù)據(jù)操作和函數(shù)調(diào)用的相關(guān)資料,希望通過本文能幫助到大家掌握這方法,需要的朋友可以參考下2017-09-09
Vue.js React與Angular流行前端框架優(yōu)勢對比
這篇文章主要為大家介紹了Vue.js React與Angular流行前端框架優(yōu)勢對比,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
Servlet3.0與純javascript通過Ajax交互的實例詳解
Servlet與純javascript通過Ajax交互,對于很多人來說應(yīng)該很簡單。不過還是寫寫,方便Ajax學(xué)習(xí)的后來者2018-03-03

