Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to narrow a union type?

How could one narrow/split/decompose a possibly discriminated union type?

For example in the following I’d like to get the type with the 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" }>;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Unless you have some use case not mentioned in the question, you can just use the provided Extract<T, U> utility type:

type Narrowed = Extract<MyUnion, { kind: "bar" }>;
/* type Narrowed = { kind: "bar"; bar: string;}

Playground link to code

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading