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

TypeScript:如何基于鉴别符移除联合类型指定分支?

基于鉴别符disc移除联合类型分支的TypeScript泛型实现

完全可以用TypeScript实现这个需求,核心是利用条件类型的分布式特性遍历联合类型的每个分支,结合鉴别符字段完成过滤。

泛型类型定义

type ExcludeByDisc<Union, DiscValues> = Union extends { disc: infer D }
  ? D extends DiscValues ? never : Union
  : Union;

逻辑说明

  • 当Union是联合类型时,TypeScript的条件类型会自动逐个处理每个分支(这是分布式条件类型的特性)。
  • 对每个分支,用infer D提取它的disc字段类型。
  • 如果提取到的D属于要排除的DiscValues集合,就返回never(never会被自动从联合类型中剔除);否则保留原分支类型。

示例验证

用你提供的联合类型测试:

type Union =
  | { disc: "a"; someField: string }
  | { disc: "b"; some: boolean; field: number }
  | { disc: "c"; foo: number }
  | { disc: "d" };

// 移除disc为"c"和"d"的分支
type UnionWithoutCAndD = ExcludeByDisc<Union, "c" | "d">;

// 手动定义的预期结果
type CAndDManuallyRemoved =
  | { disc: "a"; someField: string }
  | { disc: "b"; some: boolean; field: number };

// 此时UnionWithoutCAndD和CAndDManuallyRemoved完全等价

额外说明

如果你的联合类型中存在不包含disc字段的分支,这个泛型会直接保留该分支(因为Union extends { disc: infer D }不成立时,会走else分支返回原类型)。

内容的提问来源于stack exchange,提问作者Balázs Édes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:15:43