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.