假设我们有两个接口(interface) First
和 Second
:
interface First {
a: string;
b: number;
}
interface Second {
b: number;
c: Date;
}
通过交叉点可以合并两个接口(interface):
type FirstSecond = First & Second // {a: string, b: number, c: Date}
但是否有可能进行内部连接,因此生成的接口(interface)仅包含在两个接口(interface)中声明的属性:
type FirstSecond = First /*inner join here*/ Second // {b: number}
这对于泛型类型尤其有用。
最佳答案
您可以使用Pick
从交叉点获取公共(public)属性。要获得公共(public)属性,您可以使用 Extract
条件类型通过另一种类型的键过滤一种类型的键:
interface First {
a: string;
b: number;
}
interface Second {
b: number;
c: Date;
}
type IntersectByProperties<T, U> = Pick<T & U, Extract<keyof T, keyof U>>
type R = IntersectByProperties<First, Second>
关于typescript - 是否可以在接口(interface)上制作 "inner join",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57267935/