This article is part of the Series: Typescript utility types, in plain English
Exclude in a nutshell 🥜
Exclude is a cousin to
Omit removes properties from an object type,
Exclude removes entire types from a
Each excluded member is delimited by the 'pipe' operator |
type Role = Admin | Collaborator | User type AuthorizedRole = Exclude<Role, Collaborator | User> /* Equivalent to type AuthorizedRole = Admin */
When should you use Exclude?
Exclude can be used anytime you wish to exclude certain members from an Union to make it more restrictive.
For example, let's say you have an application similar to Hasnode. In your application, users can change the global theme of their blog.
To do so, you have all the themes available in a
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 = Exclude<Theme, PoorAccessibilityTheme> const changeMyTheme = (theme: AccessibleTheme) => /* change my theme to `theme` - implementation hidden */
That's it! Now
AccessibleThemes only include accessible themes.
Another example? Let's go!
type StartPokemon = Bulbasaur | Squirtle | Charmander type WaterStartPokemon = Exclude<StartPokemon, Bulbasaur | Charmander> // 💧 type FireStartPokemon = Exclude<StartPokemon, Bulbasaur | Squirtle> // 🔥 type GrassStartPokemon = Exclude<StartPokemon, Charmander | Squirtle> // 🥬
Exclude<UnionType, ExcludedMembers> is used when you wish to exclude entire types from a
Like any other type, it can (and should when necessary!) be combined with other utility types.