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

TypeScript中如何从联合类型中排除指定成员得到新类型

解决方案

你使用的Omit工具类型仅适用于处理对象类型的键移除,无法实现联合类型的成员过滤,所以写法不生效。

要实现你的需求,使用TypeScript内置的Exclude工具类型即可,正确写法如下:

export type ExampleX = Exclude<Example, ExampleThree>;

Exclude的作用是遍历第一个泛型参数的所有联合成员,过滤掉可以赋值给第二个泛型参数的成员,最终得到的ExampleX类型就等价于ExampleOne | ExampleTwo。


完整验证示例

// 三个基础类型定义
type ExampleOne = { type: 'one' };
type ExampleTwo = { type: 'two' };
type ExampleThree = { type: 'three' };

// 原始联合类型
export type Example = ExampleOne | ExampleTwo | ExampleThree;

// 过滤后的新类型
export type ExampleX = Exclude<Example, ExampleThree>;

此时ExampleX的实际类型就是ExampleOne | ExampleTwo,完全符合需求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 12:06:07