DEV Community

Cover image for How to easily make a new type by removing or excluding certain values from a union type in TypeScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to easily make a new type by removing or excluding certain values from a union type in TypeScript?

Originally posted here!

To easily make a new type by removing or excluding certain values from a union type in TypeScript, you need to use the Exclude utility type and pass the union type to remove the values from as its first type argument, and the union type composed of values to remove or a string if only single value as its second type argument.

TL;DR

// a simple union type
type AcceptedValues = "Hello" | "Hi" | 43 | true;

// make a new type by removing the values of `43`
// and `true` using the `Exclude` utility type
type RefinedTypes = Exclude<AcceptedValues, 43 | true>; // "Hello" | "Hi"
Enter fullscreen mode Exit fullscreen mode

For example, let's say we have a union type called AcceptedValues which is composed of values like Hello, Hi, 43 and true like this,

// a simple union type
type AcceptedValues = "Hello" | "Hi" | 43 | true;
Enter fullscreen mode Exit fullscreen mode

Now to make a new type by removing the values of 43 and true, we can use the Exclude utility type and pass the AcceptedValues type as its first type argument, and the union type composed of 43 and true as its second argument type.

It can be done like this,

// a simple union type
type AcceptedValues = "Hello" | "Hi" | 43 | true;

// make a new type by removing the values of `43`
// and `true` using the `Exclude` utility type
type RefinedTypes = Exclude<AcceptedValues, 43 | true>; // "Hello" | "Hi"
Enter fullscreen mode Exit fullscreen mode

Now if you hover over the RefinedTypes type in an editor or look into the contents of the type, you can see that the values 43 and true are excluded and only the Hello and Hi values are present in it.

We have successfully made a new type by excluding certain values from the union type in TypeScript. Yay 🥳!

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (1)

Collapse
 
mrluisfer profile image
Luis Alvarez

I love stumbling upon these random posts that are simple and easy to understand, thx!