likes
comments
collection
share

TS 类型收窄

作者站长头像
站长
· 阅读数 28

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

JS方法

  1. typeof

    缺点

    • typeof null —→ object
    • typeof 数组 —→ object
    • typeof 日期 —→ object
  2. a instanceof A : A 是否出现在a的原型链上

    缺点

    • 不支持stringnumberboolean 等原始类型

    • 不支持TS的 自定义类型,如下:

      type Person {
        name: string
      }
      
  3. key in obj

  4. 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
}

👍🏻👍🏻可辨别联合

要求: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
  }
}