TypeScript如何基于联合类型内的key提取指定联合成员类型
实现方案
你可以直接使用TypeScript内置的Extract工具类型完成需求,不需要手动枚举联合类型的每个成员。
使用示例如下:
type Thing = { type: "person", data: { name: "John" } } | { type: "building", data: { address: "111 Main Street" } } // 提取type为person的成员类型 type Person = Extract<Thing, { type: 'person' }>;
此时Person的类型就和预期完全一致:
{ type: "person", data: { name: "John" } }
如果要频繁使用这类根据指定key筛选联合类型的场景,还可以封装通用工具类型:
// 通用提取工具,可自定义要匹配的key type ExtractByKey<Union, Key extends PropertyKey, Value> = Extract<Union, Record<Key, Value>>; // 针对你的场景使用 type Person = ExtractByKey<Thing, 'type', 'person'>; type Building = ExtractByKey<Thing, 'type', 'building'>;
原理解释
Extract是TypeScript内置的条件类型工具,底层实现逻辑为:
type Extract<T, U> = T extends U ? T : never;
它会自动遍历联合类型T的每个成员,判断成员是否符合U的类型约束,符合则保留该成员,不符合则过滤为never,最终返回筛选后的联合类型。
内容的提问来源于stack exchange,提问作者TheAschr
相关产品推荐
相关产品推荐

