【问题标题】:Why does typescript give a type error on type unions?为什么打字稿在类型联合上给出类型错误?
【发布时间】:2020-11-04 16:24:05
【问题描述】:

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

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
}

当我从 typescript 访问 resultidvalue 时出现错误:

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

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

【问题讨论】:

  • 您需要type guard 以某种方式。
  • 因为result只存在于B上,如果你的objA,那么访问result就会返回undefined

标签: javascript typescript union-types


【解决方案1】:
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

【讨论】:

    【解决方案2】:

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

    type Types = A & B
    

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

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

    参考

    1. About & Intersection Types
    2. 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>()
    

    【讨论】:

    • 当然,希望得到解释。找了很久的答案
    【解决方案3】:
    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 2021-08-05
      • 2018-12-06
      • 2020-11-30
      • 1970-01-01
      相关资源
      最近更新 更多