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

TypeScript:如何从含多判别值的联合类型中提取指定类型?

TypeScript Extract提取子类型问题解决方法

问题原因

你定义的Entity类型中,user和person被归在同一个联合分支下,该分支的type字段是联合类型'user' | 'person'。而Extract工具类型的筛选逻辑是保留联合类型中可赋值给第二个参数的成员,由于这个分支的type是两个值的联合,无法完全匹配{type: 'user'},所以提取结果为never。

解决方案

方案一:自定义精准提取工具类型

编写一个工具类型,通过条件类型判断目标类型是否包含在type字段的联合类型中,实现精准提取:

type ExtractByType<T, TargetType extends string> = T extends { type: infer U }
  ? TargetType extends U
    ? T & { type: TargetType }
    : never
  : never;

// 使用示例
type User = ExtractByType<Entity, 'user'>; // { type: 'user'; id: string; }
type Person = ExtractByType<Entity, 'person'>; // { type: 'person'; id: string; }
type Animal = ExtractByType<Entity, 'animal'>; // { type: 'animal'; id: number; }

该工具类型先推断出T的type字段类型,再检查目标类型是否是它的子类型,最后返回收窄后的具体类型。

方案二:拆分原联合类型分支

如果可以调整Entity的定义,将user和person拆分为独立的联合分支,就能直接使用Extract:

type Entity =
  | { type: 'user'; id: string }
  | { type: 'person'; id: string }
  | { type: 'animal'; id: number };

type User = Extract<Entity, { type: 'user' }>; // { type: 'user'; id: string; }

拆分后每个分支的type都是单一字面量类型,Extract可以直接匹配到对应的分支。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 02:40:18