判断TypeScript联合类型的值具体是什么类型

83 阅读1分钟
  1. 使用in,检查特定的属性
  type TypeA  ={ a: number, kind: string}
  type TypeB = { b: number, kind: string}

  type UType = TypeA | TypeB

  function fn( param: UType){
    if( 'a' in param){ // 这里param会被自动推断为TypeA
      param.a // do something
    }else {
      param.b // do something
    }
  }
  1. 判断特定的属性的值
  type TypeA  ={ a: number, kind: 'a'}
  type TypeB = { b: number, kind: 'b'}

  type UType = TypeA | TypeB

  function fn( param: UType){
    if(param.kind === 'a'){
      param.a // do something
    }else{
      param.b // do something
    }
  }
  1. 错误的写法
  type TypeA  ={ a: number, kind: 'a'}
  type TypeB = { b: number, kind: 'b'}

  type UType = TypeA | TypeB

  function fn( param: UType){
    if(param.a){ // 报错:Property 'a' does not exist on type 'UType'.  Property 'a' does not exist on type 'TypeB'.ts(2339)
      param.a // do something
    }else{
      param.b // do something
    }
  }