JavaScript
主页 > 网络编程 > JavaScript >

TS 类型收窄教程示例介绍

2022-09-23 | 佚名 | 点击:

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

JS方法

typeof

缺点

a instanceof A : A 是否出现在a的原型链上

缺点

不支持string 、number 、boolean 等原始类型

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

1

2

3

type Person {

  name: string

}

????????类型谓词is

重点在 shape is Rect

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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

  }

}

原文链接:https://juejin.cn/post/7145305234007392269
相关文章
最新更新