假设我有一个接口:
// 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";
}
我的问题是是否有可能从气球中"拿走"颜色部分并将其注入衬衫,所以我得到这样的东西:
interface Shirt {
size: "m" | "l" | "xl";
color: Balloon.color; // I know this is wrong but it is to illustrate what I want to achieve
}
您可以使用基接口:
interface WithColor {
color: "red" | "blue" | "green";
}
interface Shirt extends WithColor {
size: "m" | "l" | "xl";
}
或者可以使Color
为enum:
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"];
}
interface Balloon {
diameter: number;
color: "red" | "blue" | "green";
}
type Shirt = {
size: "m" | "l" | "xl";
} & Pick<Balloon, 'color'>
type Check = Shirt['color'] // "red" | "blue" | "green"
游乐场
在这里您可以找到更多实用程序类型