Typescript类型体操 - Diff
题目
中文
获取两个接口类型中的差值属性。
type Foo = {
a: string;
b: number;
};
type Bar = {
a: string;
c: boolean;
};
type Result1 = Diff<Foo, Bar>; // { b: number, c: boolean }
type Result2 = Diff<Bar, Foo>; // { b: number, c: boolean }
English
Get an Object
that is the difference between O
& O1
答案
type MyExclude<T, K> = T extends K ? never : T;
type Diff<O extends {}, O1 extends {}> = {
[P in MyExclude<keyof O, keyof O1> | MyExclude<keyof O1, keyof O>]: (O &
O1)[P];
};