ysf*_*ran 3 typescript typescript-generics
比方说,我们有两个接口First和Second:
interface First {
a: string;
b: number;
}
interface Second {
b: number;
c: Date;
}
Run Code Online (Sandbox Code Playgroud)
使用相交可以合并两个接口:
type FirstSecond = First & Second // {a: string, b: number, c: Date}
Run Code Online (Sandbox Code Playgroud)
但是可以进行内部连接,因此结果接口仅包含在两个接口中声明的属性:
type FirstSecond = First /*inner join here*/ Second // {b: number}
Run Code Online (Sandbox Code Playgroud)
这对于泛型类型尤其有用。
您可以用来Pick从交叉点获取常用属性。要获取公共属性,可以使用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>
Run Code Online (Sandbox Code Playgroud)