如何合并两个接口类型并合并重叠属性的类型?

时间:2020-07-24 18:48:42

标签: typescript

如何编写通用类型别名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;
}

1 个答案:

答案 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.