`Extract<Type, Union>` in TypeScript

ยท

2 min read

This article is part of the Series: TypeScript utility types, in plain English

Extract in a nutshell ๐Ÿฅœ

Extract is the opposite of Exclude, in the same way, that Omit is the opposite of Pick.

With Extract, you can create a new union type from an existing union by picking which type to keep.

Ouch. That's a mouthful.

Let's see the code, that's quite simple.

Each selected member is delimited by the 'pipe' operator |

type Role = Admin | Collaborator | User

type Admin = Extract<Role, Admin>
type NonAdmin = Extract<Role, Collaborator | User>

/* 
Equivalent to

type Admin = Admin
type NonAdmin = Collaborator | User
*/

Example โœ๏ธ

When should you use Extract?

To be honest, I could not come up with an interesting example, so we are going to use the same as our Exclude article.

It's an interesting way to see how complimentary both utility types are.

type Theme = Dark | Light | PoorAccessibilityTheme

const changeMyTheme = (theme: Theme) => /* change my theme to `theme` - implementation hidden */

changeMyTheme(Dark) // ๐ŸŸข Changing my theme to `Dark`

Let's say that users can also choose to only use themes that respect accessibility rules.

type AccessibleTheme = Extract<Theme, Dark | Light>

const changeMyTheme = (theme: AccessibleTheme) => /* change my theme to `theme` - implementation hidden */

That's it! Now AccessibleThemes only include accessible themes.

Let's see another example:

type Instrument = Guitar | Bass | Saxophone

type WoodwindInstrumentFamily = Extract<Instrument, Saxophone> // ๐ŸŽท
type StringInstrumentFamily = Extract<Instrument, Guitar | Bass> // ๐ŸŽธ

Conclusion โ˜๏ธ

Extract<Type, Union> is used when you need to create a union type from an existing union type.

Like any other type, it can (and should when necessary!) be combined with other utility types.

ย