美文网首页
联合类型 |

联合类型 |

作者: RickyWu585 | 来源:发表于2022-11-09 17:39 被阅读0次
    • 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

    相关文章

      网友评论

          本文标题:联合类型 |

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