【TS】如何在 typescript 中合并一个 interface union?
warning:
这篇文章距离上次修改已过448天,其中的内容可能已经有所变动。
在 TypeScript 中,你可以使用 & 操作符来合并两个 interface,或者使用 extends 关键字。当你想要合并多个 interface 时,可以使用 | 操作符来表示 union types。
例如,假设你有两个 interface A 和 B,你想要创建一个新的 interface C,它同时包含 A 和 B 的所有成员。
interface A {
x: number;
y: string;
}
interface B {
y: number;
z: boolean;
}
// 方法一:使用 & 操作符
interface C1 extends A, B {}
// 方法二:使用 intersection type
type C2 = A & B;在这个例子中,C1 和 C2 都会包含 x 类型为 number,y 类型为 string | number,以及 z 类型为 boolean 的属性。
如果你想要创建一个新的 interface,它可以是 A 或者 B 的任何一个,你可以使用 type alias 和 union types。
// 使用 union type
type D = A | B;在这个例子中,D 可以是 { x: number; y: string; } 或者 { y: number; z: boolean; }。
评论已关闭