How to Omit values from an Enum in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 14, 2022

banner

Photo from Unsplash

Omit values from an Enum in TypeScript #

Use the Exclude utility type to omit values from an enum, e.g. type WithoutMultiple = Exclude<Sizes, Sizes.Small | Sizes.Medium>. The Exclude utility type constructs a new type by excluding the provided members from the original type.

index.ts
// ✅ For Numeric Enums enum Sizes { Small, Medium, Large, ExtraLarge, } // 👇️ type WithoutSmall = Sizes.Medium | Sizes.Large | Sizes.ExtraLarge type WithoutSmall = Exclude<Sizes, Sizes.Small>; // 👇️ type WithoutMultiple = Sizes.Large | Sizes.ExtraLarge type WithoutMultiple = Exclude<Sizes, Sizes.Small | Sizes.Medium>;

We used the Exclude utility type to omit values from the enum.

Type first type we passed to Exclude is the enum itself and the second - the values we want to exclude.

Note that we could also directly pass the values without accessing them on the enum.

index.ts
enum Sizes { Small, Medium, Large, ExtraLarge, } // 👇️ type WithoutSmall = Sizes.Medium | Sizes.Large | Sizes.ExtraLarge type WithoutSmall = Exclude<Sizes, 0>;

The first member in a numeric enum without an initial value has a value of 0.

This approach would also work with a string enum.

index.ts
enum Sizes { Small = 'S', Medium = 'M', Large = 'L', ExtraLarge = 'XL', } // 👇️ type WithoutSmall = Sizes.Medium | Sizes.Large | Sizes.ExtraLarge type WithoutSmall = Exclude<Sizes, Sizes.Small>; // 👇️ type WithoutMultiple = Sizes.Large | Sizes.ExtraLarge type WithoutMultiple = Exclude<Sizes, Sizes.Small | Sizes.Medium>;

You could also pass the values of the string enum directly, without referencing them on the enum.

index.ts
enum Sizes { Small = 'S', Medium = 'M', Large = 'L', ExtraLarge = 'XL', } // 👇️ type WithoutSmall = Sizes.Medium | Sizes.Large | Sizes.ExtraLarge type WithoutSmall = Exclude<Sizes, 'S'>; // 👇️ type WithoutMultiple = Sizes.Large | Sizes.ExtraLarge type WithoutMultiple = Exclude<Sizes, 'S' | 'M'>;

An easy way to visualize how the Exclude utility type works is to use a union type.

index.ts
type U = 'a' | 'b' | 'c'; // 👇️ type T1 = "a" | "b" type T1 = Exclude<U, 'c'>; // 👇️ type T2 = "a" type T2 = Exclude<U, 'c' | 'b'>;

The first type we passed to Exclude is the union type and the second - the types we want to omit for the constructed type.

If you need to exclude multiple types, make sure to separate them with a pipe |, and not a comma or a semicolon.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.