Last updated: Feb 26, 2024
Reading timeยท2 min
Use the Exclude
utility type to omit values from an enum.
The Exclude
utility type constructs a new type by excluding the provided
members from the original type.
// โ 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.
Exclude
is the enum itself and the second is the values we want to exclude.We could also directly pass the values without accessing them on the enum.
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.
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.
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.
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 is 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.
If you need to check if a value exists in an enum, click on the following article.
You can learn more about the related topics by checking out the following tutorials: