如何编写通用类型别名Combine<A, B>
,该别名组合了任意两个接口A和B,同时保留了两者的匹配属性,但使用并集合并了属性类型?
例如,使用以下两个界面:
interface Interface1 {
type: string;
another: bool;
}
interface Interface2 {
type: number;
}
然后,Combine<Interface1, Interface2>
的类型应为:
type Result = {
type: string | number;
another: bool;
}
答案 0 :(得分:3)
首先获取A中所有不在B中的键,以及B中不在A中的键,并为键的交集明确定义并集:
type Combine<A, B> =
Omit<A, keyof B> // items in A that aren't in B
& Omit<B, keyof A> // items in B that aren't in A
& { [K in keyof A & keyof B]: A[K] | B[K] }; // union of both.
请注意,指示其中一个而不存在于另一个中的键可能会有所帮助,因此您可以在Partial
上使用Omit
:
type Combine<A, B> =
Partial<Omit<A, keyof B>> // possibly items in A that aren't in B
& Partial<Omit<B, keyof A>> // possibly items in B that aren't in A
& { [K in keyof A & keyof B]: A[K] | B[K] }; // union of both.