DEV Community

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

Posted on • Originally published at melvingeorge.me

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

Originally posted here!

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"
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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


Top comments (0)