You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过key字段从TypeScript联合类型中获取指定子类型

从联合类型中通过指定key字段提取对应子类型的实现方法

完全可以实现,借助TypeScript的条件类型分布式特性就能做到。

针对type字段的专属实现

针对你给出的场景,直接实现SomeCoolType:

type T1 = {type: 'a', a1: string, a2: boolean}
type T2 = {type: 'b', b1: string}
type T3 = {type: 'c', c1: number}

type UnionT = T1 | T2 | T3

// 核心类型实现
type SomeCoolType<T extends {type: string}, S extends T["type"]> = 
  T extends {type: S} ? T : never;

// 验证结果
type AType = SomeCoolType<UnionT, 'a'>; // 类型为 {type: 'a', a1: string, a2: boolean}
type BType = SomeCoolType<UnionT, 'b'>; // 类型为 {type: 'b', b1: string}
type CType = SomeCoolType<UnionT, 'c'>; // 类型为 {type: 'c', c1: number}

原理很直接:当泛型参数T是联合类型时,条件类型会自动遍历联合类型的每个成员,只保留那些type字段匹配S的子类型,过滤掉不匹配的成员(返回never)。

更通用的版本(支持任意key字段)

如果需要适配任意key字段,而不只是type,可以扩展成下面的通用类型:

// 通用提取类型:从联合类型T中提取key为K、值为V的子类型
type ExtractByKey<T, K extends keyof T, V extends T[K]> = 
  T extends Record<K, V> ? T : never;

// 使用示例
type AType2 = ExtractByKey<UnionT, 'type', 'a'>; // 结果和AType一致

内容的提问来源于stack exchange,提问作者Edgar Abgaryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:14:51