如何省略打字稿联合类型中的值

mee*_*eez 41 typescript

我有一个类型:

export type Example = ExampleOne | ExampleTwo | ExampleThree;
Run Code Online (Sandbox Code Playgroud)

如何创建ExampleX仅包含ExampleOneor的新类型ExampleTwo

我试过:

export type ExampleX = Omit<Example, 'ExampleThree'>;
Run Code Online (Sandbox Code Playgroud)

但这不起作用吗?

T.J*_*der 72

您正在寻找Exclude而不是Omit

Exclude<UnionType, ExcludedMembers>

通过从 UnionType 中排除所有可分配给 ExcludedMembers 的联合成员来构造类型。

(而且你不需要引号。)

所以:

export type ExampleX = Exclude<Example, ExampleThree>;
Run Code Online (Sandbox Code Playgroud)

游乐场链接