💡 理解方式
Extract 的核心是交集运算
// 把 Extract 理解为"取交集"
type Result = Extract<集合A, 集合B>
// Result = 集合A 和 集合B 的交集
🎯 重新举例
例子1:从多个中提取
type Animals = 'cat' | 'dog' | 'bird' | 'fish'
// 提取 Animal 中 和 ('cat' | 'dog') 有交集的部分
type Pets = Extract<Animals, 'cat' | 'dog'>
// Pets = 'cat' | 'dog'
// 因为 Animals 中有 'cat' 和 'dog'
例子2:部分匹配
type Colors = 'red' | 'blue' | 'green' | 'yellow'
// 提取 Colors 中 和 ('blue' | 'purple') 有交集的部分
type SomeColors = Extract<Colors, 'blue' | 'purple'>
// SomeColors = 'blue' (只有 'blue' 匹配)
// 因为 Colors 中没有 'purple'
例子3:完全不匹配
type Fruits = 'apple' | 'banana' | 'orange'
// 提取 Fruits 中 和 ('grape' | 'watermelon') 有交集的部分
type NoMatch = Extract<Fruits, 'grape' | 'watermelon'>
// NoMatch = never (没有交集)
📊 用数学集合理解
集合A: {猫, 狗, 鸟, 鱼}
集合B: {猫, 狗}
交集: {猫, 狗} ← Extract<集合A, 集合B>🔧 实际的实用场景
场景1:权限过滤
// 所有可能的权限
type AllPermissions =
| 'user:read'
| 'user:write'
| 'admin:read'
| 'admin:write'
| 'super:all'
// 用户角色拥有的权限
type UserPermissions = 'user:read' | 'user:write'
// 提取用户实际可用的权限
type AvailableForUser = Extract<AllPermissions, UserPermissions>
// AvailableForUser = 'user:read' | 'user:write'
场景2:API 端点过滤
// 所有 API 端点
type AllEndpoints =
| '/api/users'
| '/api/devices'
| '/api/alarms'
| '/api/logs'
| '/api/admin/users'
// 公开的端点(无需认证)
type PublicEndpoints = '/api/users' | '/api/devices'
// 提取公开端点
type AvailablePublicEndpoints = Extract<AllEndpoints, PublicEndpoints>
// AvailablePublicEndpoints = '/api/users' | '/api/devices'
🆚 对比:有 Extract vs 没有 Extract
没有 Extract
// 需要手动检查
type DeviceStatus = 'online' | 'offline' | 'error' | 'warning'
// 容易出错
type AlertStatus = 'error' | 'warning' // 手动维护,可能遗漏
有 Extract
// 自动推导
type DeviceStatus = 'online' | 'offline' | 'error' | 'warning'
type AlertStatus = Extract<DeviceStatus, 'error' | 'warning'>
// 自动确保 AlertStatus 是 DeviceStatus 的子集
🔄 自动类型同步
// 当基础类型变化时
type DeviceStatus =
| 'online'
| 'offline'
| 'error'
| 'warning'
| 'disconnected' // 新增
// AlertStatus 会自动更新
type AlertStatus = Extract<DeviceStatus, 'error' | 'warning' | 'disconnected'>
// AlertStatus = 'error' | 'warning' | 'disconnected' ← 自动包含新的
⚡ TypeScript 的智能
Extract 让 TypeScript 帮你自动推理类型关系,而不是手动维护类型对应关系。
🎯 一句话总结
Extract 是 TypeScript 的”类型交集”工具,它找出两个类型集合中都存在的类型。
