联合类型 |

  • A | B并集的意思,既可以是A也可以是B,也可以是A和B的交集
type A = {
  name:string
}
type B = {
  age: number
}

type C = A | B

const a1:C = {
  age:18
}
const a2:C = {
  name:"frank"
}
const a3:C = {
  name:"frank",
  age:18
}
  • 但是当 type A = string | number 时就类型特性就不好用了,因此需要进行类型收窄
  1. typeof:缺点是只支持基本类型,不具体
type A = string | number

const fn = (a:A) => {
  if(typeof a === "number"){
    a.toFixed()
  }else{
    a.split()
  }
} 
  1. instanceof,缺点是不支持string,number等基本类型,不支持TS独有的类型
const fn = (a: Date | Date[]) =>{
  if(a instanceof Date){

  }else if(a instanceof Array){

  }
}
  1. in,缺点是只适用于部分对象
type Person = {
  name: string
}

type Animal = {
  action: string
}

const fn  = (a:Person | Animal) =>{
  if('name' in a){
    a.name
  }else if('action' in a){
    a.action
  }
}
  • 类型收窄通用方法
  1. 类型谓词 is,缺点是麻烦
type Rect = {
  height: number
  width: number
}

type Circle = {
  center: [number,number]
  radius: number
}

const fn = (a: Rect | Circle) => {
  if(isRect(a)){
     a.height
  }else {
    a.center
  }
}

// is这里是必须是普通函数
function isRect(x: Rect | Circle): x is Rect{
  return 'height' in x && 'width' in x
}

function isCircle(x: Rect | Circle): x is Circle{
  return 'center' in x && 'radius' in x
}
  1. 可辨别联合:加一个可辨别的字段,这个字段只能是基本类型,且可区分
type Circle = {
  kind: "Circle"
  center: [number,number]
}

type Square = {
  kind: "Squrae"
  sideLength: number
}

const fn = (a: string | number | Circle | Square) => {
  if(typeof a === "string"){

  }else if(typeof a === "number"){

  }else if(a.kind === "Circle"){

  }else if(a.kind === "Squrae"){

  }
}
  1. 强制断言as
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容