如何缩小联合类型?

Qta*_*tax 8 typescript typescript-generics

如何缩小/分裂/分解一种可能受歧视的联合类型?

kind: "bar"例如,在下面我想获取来自from的类型MyUnion

type MyUnion = { kind: "foo", foo: number } | { kind: "bar", bar: string };

// Here I want to somehow get the type { kind: "bar", bar: string } from MyUnion
type Narrowed = NarrowUnion<MyUnion, { kind: "bar" }>;
Run Code Online (Sandbox Code Playgroud)

jca*_*alz 8

除非您有问题中未提及的某些用例,否则您可以仅使用提供的Extract<T, U>实用程序类型

type Narrowed = Extract<MyUnion, { kind: "bar" }>;
/* type Narrowed = { kind: "bar"; bar: string;}
Run Code Online (Sandbox Code Playgroud)

Playground 代码链接