【问题标题】:How to inherit properties from only one of the types in a union of interfaces如何仅从接口联合中的一种类型继承属性
【发布时间】:2020-04-08 08:51:52
【问题描述】:

如何使对象x 仅具有来自ABC 之一的属性。目前,它可以拥有所有属性abc,我只希望它是其中之一,而不是其他属性。

interface A {
  a: string;
}
interface B {
  b: string;
}
interface C {
  c: string;
}

type X = A | B | C;

const x: X = {
  a: 'a',
  b: 'b',
  c: 'c'
};

console.log(x); // returns { a: "a", b: "b", c: "c" }, should throw error.

Typescript 版本 - 3.8.3

【问题讨论】:

    标签: typescript interface union


    【解决方案1】:

    查看 TypeScript 文档 (here) 我不确定这是否可以使用接口(我很可能是错的)。但我确实设法使用 Enums 实现了您正在寻找的东西。

    enum A {
      a = 'a'
    }
    enum B {
      b = 'b'
    }
    enum C {
      c = 'c'
    }
    
    type X = A | B | C;
    
    const x: X = {
      a: 'a',
      b: 'b',
      c: 'c'
    };
    /* This does throw an error:
    Type '{ a: string; b: string; c: string; }' is not assignable to type 'X'.
      Type '{ a: string; b: string; c: string; }' is not assignable to type 'C'.
    

    【讨论】:

    • 但枚举只支持stringnumber 我需要这是一个接口,因为属性将是嵌套对象。我仅以字符串为例。
    猜你喜欢
    • 2014-11-21
    • 1970-01-01
    • 2021-06-13
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 2019-12-02
    相关资源
    最近更新 更多