在 TypeScript 类型系统中,工具类型为我们提供了强大的类型操作能力。其中,Omit 是一个实用的工具类型,它从一个对象类型中“剔除”某些属性,从而生成一个新的类型。
定义如下:
//从类型 T 中移除键为 K 的属性,返回一个新类型
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>
示例
interface User {
id: number;
name: string;
email: string;
password: string;
}
// 剔除敏感字段 password
type PublicUser = Omit<User,password>;
// 等价于:
// type PublicUser = {
// id: number;
// name: string;
// email: string;
// };
Omit 的实现:
要理解 Omit,需要先了解两个基础工具类型:Pick 和 Exclude。
- Exclude<T,U>
从联合类型 T 中排除所有可赋值给 U 的类型。
type A = Exclude<'a' | 'b' | 'c', 'b'>; // 'a' | 'c'
- Pick
从类型 T 中挑选出键为 K 的属性。
type B = Pick<{ a: 1; b: 2; c: 3 }, 'a' | 'c'>; // { a: 1; c: 3 }
Omit 的实现方式是:
获取 T 的所有键:keyof T
从中排除掉 K:Exclude<keyof T, K>
用剩下的键从 T 中挑选属性:Pick<T, ...>
因此:
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
如果使用非内置工具类型自定义实现 MyOmit,方式如下:
type MyOmit<T, K extends keyof T> = {
[P in keyof T as P extends K ? never:P]: T[P]
}
type OmitData = MyOmit<{a:1,b:2}, 'a'>
//OmitData等价于
type OmitData = {
b: 2;
}
总结:
Omit 是 TypeScript 类型编程中的利器,它通过组合 Pick 和 Exclude 实现了属性剔除。理解其内部机制不仅能帮助我们更高效地使用它,还能启发我们构建更复杂的自定义工具类型。

1105

被折叠的 条评论
为什么被折叠?



