TS-4 类型收窄

作者: RickyWu585 | 来源:发表于2023-03-10 18:06 被阅读0次
  • 联合类型 |,是求并集
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
}
  • 注意:


    image.png
  • 针对联合类型,有时需要进行类型收窄才能继续
  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,强制收缩
  • unknown 类型可以被类型收窄成任何类型,相当于是所有类型的联合类型

相关文章

  • typescript学习笔记-类型收窄

    // typeof 类型收窄// 使用类型陈述语法实现类型收窄

  • TypeScript 中的类型收窄

    在本文中,我们将学习各种收窄类型的方法。类型(narrowing)收窄是将类型从不太精确的类型推导为更精确的类型的...

  • 第十节: TypeScript 类型收窄

    类型收窄 所谓的类型收窄, 就是当我们定义类型描述为了适应多种尝试使用,变量可能是多种类型, 此时在处理不同类型数...

  • typescript中的类型保护

    类型保护: 当使用联合类型时, 我们必须尽量把当前值的类型收窄为当前值的实际类型,类型保护就是可执行运行时检查的一...

  • 协变与逆变

    协变:用窄类型替代宽类型,如子类代替父类,符合里氏替换原则 逆变:用宽类型替代窄类型,与里氏替换相反,所以叫“逆”...

  • 宽窄字符

    头文件: 窄字符 char 类型 宽字符 wchar_t 类型 通用类型

  • 窄化类型转换

    窄化类型转换(Narrowing Numeric Conversion) 1.转换规则 Java虚拟机也直接支持以...

  • 2018-06-06

    一、遇到百分点,直接相加减 ;遇到降幅,收窄、扩大、收窄等,同比下降4.7%,eg:降幅扩大1.3个百分点。(4....

  • java int和byte转换

    int转byte 在java中,宽类型(wider integer type)转窄类型(narrower type...

  • 来了,新鲜资讯

    【早盘:纳指与标普涨幅显著收窄 道指转跌】 美股周二早盘走势疲软,道指转跌,纳指与标普涨幅显著收窄。 昨日美股大幅...

网友评论

    本文标题:TS-4 类型收窄

    本文链接:https://www.haomeiwen.com/subject/pucukdtx.html