JavaScript

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > TS 类型收窄

TS 类型收窄教程示例详解

作者:dingsheng

这篇文章主要为大家介绍了TS 类型收窄教程示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

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

JS方法

typeof

缺点

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

缺点

不支持stringnumberboolean 等原始类型

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

type Person {
  name: string
}

👍🏻类型谓词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

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 类型收窄教程示例详解的详细内容,更多关于TS 类型收窄的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文