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

Why does typescript give a type error on type unions?

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

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
}

当我从打字稿访问 resultidvalue 时出现错误:

Property 'result' does not exist on type 'Types'.
  Property 'result' does not exist on type 'A'

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

如果您想要执行该操作,可以使用 & 运算符 喜欢

type Types = A & B

您可以合并A接口和B接口。它正在命名 交叉点类型

我可以写一些关于这个的信息。你能等几分钟吗?

参考

  1. About Union Tpyes

现在我知道我得到的是错误的。所以如果你想使用类型 gaurd,它适合你。

enum ALPHA_TYPE {
   A = "A",
   B = "B"
}
interface A {
   ...
}
interface B {
   ...
}
export type Types<T extends ALPHA_TYPE> = T extends A ? A : B

function test<T>(obj: Types<T>) {
  obj.result;  // want to work with obj as though it implements interface B
}

你可以像这样使用

text<ALPHA_TYPE.A>()
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;
  }
}

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

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

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

interface B {
  result: string;
}

 type Types = A | B;

function test(obj: Types) {
  const objB = obj as B; // Introduce a new variable and cast it as B
  objB.result; // Happy!!!
}

只需引入一个新变量并将其转换为 B,然后您就可以对该对象调用 .result