How to easily make a new type by removing null or undefined values from the union type in TypeScript?

Published May 17, 2022

To easily make a new type by removing all the undefined and null values from the union type in TypeScript, we can use the NonNullable utility type and pass the union type to remove the null and undefined as its first type argument.

TL;DR

// a simple union type
type MyType = "Hi" | "Hello" | null | undefined;

// make a new type by excluding
// the `null` and `undefined` values
// from the `MyType` type
// using the `NonNullable` utility type
type RevisedType = NonNullable<MyType>; // "Hi" | "Hello"

For example, let's say we have a union type composed of some values including the null and undefined values like this,

// a simple union type
type MyType = "Hi" | "Hello" | null | undefined;

Now to make a new type by excluding the null, undefined values from the MyType type, we can use the NonNullable utility type and pass the MyType type as the first type argument.

It can be done like this,

// a simple union type
type MyType = "Hi" | "Hello" | null | undefined;

// make a new type by excluding
// the `null` and `undefined` values
// from the `MyType` type
// using the `NonNullable` utility type
type RevisedType = NonNullable<MyType>; // "Hi" | "Hello"

As you can see from the above code that null and undefined values are not present in the RevisedType type.

We have successfully made a new type by removing the non-nullable values from a union type in TypeScript. Yay 🥳!

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter