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
相关产品推荐
相关产品推荐

