从联合类型字符串中选择

Coo*_*ter 12 typescript

我有一个联合类型,我想从联合类型中选择某些值。这可能吗?我尝试过使用“Pick”,但这不适用于联合类型。

例如

type FooType = 'foo' | 'bar' | 'baz';
type Extracted = : Pick<FooType, 'foo' | 'bar'>; // should contains only 'foo' and 'bar'
Run Code Online (Sandbox Code Playgroud)

我现在尝试了各种策略,但无法使其发挥作用。

mig*_*aus 19

尝试使用Extract而不是Pick

type FooType = 'foo' | 'bar' | 'baz';
type Extracted = Extract<FooType, 'foo' | 'bar'>;
// type Extracted = 'foo' | 'bar'
Run Code Online (Sandbox Code Playgroud)

  • 这样做的一个主要不便之处在于,它允许您选择无效的内容而不给出编译时错误,例如 Extract&lt;FooType, 'foo' | 'bing'&gt; =&gt; 'foo'。 (4认同)