Alo
Alo

Alo

`Exclude<UnionType, ExcludedMembers>` in TypeScript

Photo by Mercvrie on Unsplash

`Exclude<UnionType, ExcludedMembers>` in TypeScript

Alo's photo
Alo
ยทApr 18, 2022ยท

2 min read

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

Exclude in a nutshell ๐Ÿฅœ

Exclude is a cousin to Omit. where Omit removes properties from an object type, Exclude removes entire types from a Union type.

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
*/

Example โœ๏ธ

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 Union type.

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> // ๐Ÿฅฌ

Conclusion โ˜๏ธ

Exclude<UnionType, ExcludedMembers> is used when you wish to exclude entire types from a Union.

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

ย 
Share this