Omit<T, K>
此工具可认为是适用于键值对对象的 Exclude,它会去除类型 T 中包含 K 的键值对。
/**
* Construct a type with the properties of T except for those in type K.
*/
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
在定义中,第一步先从 T 的 key 中去掉与 K 重叠的 key,接着使用 Pick 把 T 类型和剩余的 key 组合起来即可。可以发现,Omit 与 Pick 得到的结果完全相反,一个是取非结果,一个取交结果。
type Person = {
name: string;
age: number;
};
type A = Exclude<keyof Person, "name" | "age">;
// ==> type A = never
type B = Pick<Person, A>;
// ==> type B = {}
const haha: Omit<Person,'name'|'age'> = { name:'dafda' };
// ==> const haha:{} = { name: 'dafda' }