为什么打字稿会在类型联合上给出类型错误?

Lou*_*upi 6 javascript typescript union-types

每当我必须使用具有组合联合类型的对象时,打字稿都会抱怨我尝试访问的属性,并且我也没有获得自动完成功能。例如这个:

interface A {
  id: string;
  value: number;
}

interface B {
  result: string;
}

export type Types = A | B;

function test(obj: Types) {
  obj.result;  // want to work with obj as though it implements interface B
}
Run Code Online (Sandbox Code Playgroud)

当我从打字稿访问resultid、 时,出现错误:value

Property 'result' does not exist on type 'Types'.
  Property 'result' does not exist on type 'A'
Run Code Online (Sandbox Code Playgroud)

有什么方法可以缩小接口类型,以便获得更好的 IDE 体验吗?

lei*_* li 6

interface A {
  type:'A';
  id: string;
  value: number;
}

interface B {
  type:'B';
  result: string;
}

export type Types = A | B;

function test(obj: Types) {
  if(obj.type==='B'){
    obj.result;
  }
}
Run Code Online (Sandbox Code Playgroud)

你需要一个公共字段来教 TS 如何识别 A 类型或 B 类型。

https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions