亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

TS 類型收窄教程示例詳解

 更新時(shí)間:2022年09月20日 14:20:34   作者:dingsheng  
這篇文章主要為大家介紹了TS 類型收窄教程示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

類型收窄之前只能使用公共方法

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)文章

最新評(píng)論