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 类型可以被类型收窄成任何类型,相当于是所有类型的联合类型

    相关文章

      网友评论

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

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