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

May 16, 2022 - 2 min read

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"

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;

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"

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 😃.