-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
一、核心对比表
| 工具类型 | 作用对象 | 核心操作 | 典型场景 | 示例 |
|---|---|---|---|---|
Omit<T, K> |
对象类型 | 排除指定属性 | 移除对象中不需要的属性 | Omit<User, 'id'> → 移除 id 属性 |
Pick<T, K> |
对象类型 | 选取指定属性 | 提取对象中需要的属性 | Pick<User, 'name'> → 仅保留 name |
Exclude<T, U> |
联合类型 | 排除匹配类型 | 过滤联合类型中的无效成员 | Exclude<1|'a', string> → 1 |
Extract<T, U> |
联合类型 | 提取匹配类型 | 筛选联合类型中的有效成员 | Extract<1|'a', string> → 'a' |
二、核心区别
- 操作维度不同
- 对象维度:
Omit和Pick操作对象类型的属性 - 联合类型维度:
Exclude和Extract操作联合类型的成员
- 行为互补
Omit↔Pick:互为反向操作(排除属性 vs 选择属性)Exclude↔Extract:互为反向操作(排除类型 vs 选择类型)
- 实现依赖
// Omit 依赖 Exclude 和 Pick
type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
// Exclude 和 Extract 基于条件类型
type Exclude<T, U> = T extends U ? never : T;
type Extract<T, U> = T extends U ? T : never;三、组合使用示例
- 动态生成对象键
interface Config {
apiUrl: string;
timeout: number;
retry: boolean;
}
// 排除非字符串键 → 提取字符串类型的键
type StringKeys = Extract<keyof Config, string>; // 'apiUrl' | 'timeout' | 'retry'
type StringConfig = Pick<Config, StringKeys>; // 等效 Config 本身- 安全类型过滤
type UserResponse = {
id: string;
name: string;
passwordHash: string;
};
// 排除敏感字段(Omit) + 提取非函数类型(Extract)
type SafeUser = Omit<UserResponse, 'passwordHash'>;
type SafeKeys = Extract<keyof SafeUser, string>; // 'id' | 'name'四、一句话总结
- 操作对象属性:用
Omit(排除)或Pick(选择) - 操作联合类型:用
Exclude(排除)或Extract(提取) - 组合使用:
keyof T + Exclude/Extract可实现维度转换,处理复杂类型逻辑