【问题标题】:Can I extend part of an Interface in Typescript? [duplicate]我可以在 Typescript 中扩展接口的一部分吗? [复制]
【发布时间】:2023-03-23 22:20:01
【问题描述】:

假设我有一个界面:

// I get this from an external library so I have no control over it
interface Balloon {
  diameter: number;
  color: "red" | "blue" | "green";
}

我想创建自己的界面,如下所示:

interface Shirt {
  size: "m" | "l" | "xl";
  color: "red" | "blue" | "green";
}

我的问题是是否可以从 Balloon 中“取出”颜色部分并将其注入到 Shirt 中,所以我得到了这样的东西:

interface Shirt {
  size: "m" | "l" | "xl";
  color: Balloon.color; // I know this is wrong but it is to illustrate what I want to achieve
}

【问题讨论】:

  • 当然。 color: Balloon['color']
  • @ritaj 您可以将其发布为答案
  • 是的,非常简单优雅的解决方案和非常快速的响应,谢谢!

标签: typescript


【解决方案1】:

您可以使用基本接口:

interface WithColor {
    color: "red" | "blue" | "green";
}

interface Shirt extends WithColor {
  size: "m" | "l" | "xl";
}

或者您可以将Color 设为枚举:

enum Color {
    RED = "red",
    BLUE = "blue",
    GREEN = "green",
}

interface Shirt {
  size: "m" | "l" | "xl";
  color: Color;
}

...甚至是这两者的结合。

虽然我不建议使用其他接口类型,因为这会带来可维护性风险,但如果您碰巧在源接口上更改它,这也是一种可能的方式:

interface Shirt {
  size: "m" | "l" | "xl";
  color: "red" | "blue" | "green";
}

interface Balloon {
  size: "m" | "l" | "xl";
  color: Shirt["color"];
}

【讨论】:

  • 问题是关于使用现有接口中的属性类型
  • @ritaj 虽然这是真的,但这不是一个好主意,因为它会降低可维护性。但是,我在答案中添加了请求的解决方案。
【解决方案2】:
interface Balloon {
    diameter: number;
    color: "red" | "blue" | "green";
}


type Shirt = {
    size: "m" | "l" | "xl";
} & Pick<Balloon, 'color'>

type Check = Shirt['color'] // "red" | "blue" | "green"

Playground

Here你可以找到更多的实用程序类型

【讨论】:

    猜你喜欢
    • 2018-12-01
    • 2016-08-16
    • 1970-01-01
    • 2013-11-02
    • 1970-01-01
    • 2017-10-21
    • 2016-07-06
    • 2017-05-14
    相关资源
    最近更新 更多