js css html

TS-4 类型收窄

2023-03-10  本文已影响0人  RickyWu585
type A = {
  name:string
}

type B = {
  age:number
}

type C = A | B

const p1:C = {
  name: 'frank'
}
const p2:C = {
  age: 18
}
// p3 处于两者交集当中,可以理解为p3有name属性,所以是属于A类型的。
const p3:C = {
  name:'frank',
  age:18
}
  1. typeof a === 'xxx':只能判断基本类型以及function
  2. arr instanceof Array:不能判断基本类型,以及TS独有的类型
  3. name in p:判断某个key是不是在对象里,只适用于部分普通对象
  4. is:类型谓词,可以作为通用方法,必须是普通函数不能是箭头函数,缺点是比较麻烦
type Rect = {
  width: number
  height: number
}
type Circle = {
  center: [number,number]
  radius: number
}

// 如果是 boolean 的话,下面a类型还是 Rect | Circle
function isRect(x:Rect | Circle):boolean{
  return 'width' in x && 'heght' in x
}

// 如果是 is 的话,下面a类型就可以推断出是Rect类型
function isRect(x:Rect | Circle): x is Rect{
  return 'width' in x && 'heght' in x
}

const fn = (a:Rect | Circle)=>{
  if(isRect(a)){
    console.log(a);
  }
}
  1. 可辨别联合类型:给各个类型加个kind来区分,kind必须是简单类型,不能是复杂类型。这种方法的目的是让复杂类型的对比变成简单类型的对比
type Rect = {
  kind: 'Rect'
  width: number
  height: number
}
type Circle = {
  kind: 'Circle'
  center: [number,number]
  radius: number
}
type Shape = Rect  | Circle 
const fn = (x: Shape ) => {
  if(x.kind === 'Rect'){
    x // Rect
  }else if (x.kind === 'Circle'){
    x // Circle
  }
}
  1. 断言 as,强制收缩
上一篇 下一篇

猜你喜欢

热点阅读