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 get specific type from union type by key field

I’d like to get subtype from a union type via key field. Is it possible?

type T1 = {type: 'a', a1: string, a2: boolean}
type T2 = {type: 'b', b1: string}
type T3 = {type: 'c', c1: number}
// ...

type UnionT = T1 | T2 | T3 // ...

type SomeCoolType<T extends {type: string}, S extends T["type"]> = T // ... is it possible?

type SomeCoolType<UT, 'a'> // === {type: 'a', a1: string, a2: boolean}
type SomeCoolType<UT, 'b'> // === {type: 'b', b1: string}
// ...

>Solution :

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

What you are looking for is a built-in Extract utility type, that allows to retrieve members of a union if they extend the second argument:

type SomeCoolType<T extends { type: string }, S extends T['type']> = Extract<T, { type: S }>;

Usage:

type Case1 = SomeCoolType<UnionT, 'a'>; // === {type: 'a', a1: string, a2: boolean}
type Case2 = SomeCoolType<UnionT, 'b'>; // === {type: 'b', b1: string}

playground

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