Remove Null and Undefined from a Type in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 9, 2022

banner

Photo from Unsplash

Remove Null and Undefined from a Type in TypeScript #

Use the NonNullable utility type to remove null and undefined from a type in TypeScript. The NonNullable utility type constructs a new type with null and undefined excluded from the type.

index.ts
// ✅ Exclude null and undefined from Type // 👇️ type T0 = string type T0 = NonNullable<null | undefined | string>; // ✅ Remove nullable types from the type's keys type WithoutNullableKeys<Type> = { [Key in keyof Type]-?: WithoutNullableKeys<NonNullable<Type[Key]>>; }; type Employee = { name?: string | null; country?: string | null; salary?: number | null; }; // 👇️ type T1 = { // name: string; // country: string; // salary: number; // } type T1 = WithoutNullableKeys<Employee>;

The first example in the code snippet uses the NonNullable utility type.

The utility type excludes null and undefined from the passed in type.

index.ts
type Salary = null | undefined | number; // 👇️ type T2 = number type T2 = NonNullable<Salary>;

However, in some situations you might need to use the NonNullable type recursively, to make all of the keys in a type non-nullable.

index.ts
type WithoutNullableKeys<Type> = { [Key in keyof Type]-?: WithoutNullableKeys<NonNullable<Type[Key]>>; }; type Employee = { name?: string | null; country?: string | null; salary?: number | null; }; // 👇️ type T1 = { // name: string; // country: string; // salary: number; // } type T1 = WithoutNullableKeys<Employee>;

The -? syntax is called a mapping modifier and is used to set the attributes of a type to required (remove optionality).

index.ts
type Employee = { name?: string | null; country?: string | null; salary?: number | null; }; type Concrete<Type> = { [Key in keyof Type]-?: Type[Key]; }; // 👇️ type T2 = { // name: string | null; // country: string | null; // salary: number | null; // } type T2 = Concrete<Employee>;

The example above shows how the Concrete type makes all of the keys in Employee required.

This approach can also be used to remove null and undefined from an interface.

index.ts
type WithoutNullableKeys<Type> = { [Key in keyof Type]-?: WithoutNullableKeys<NonNullable<Type[Key]>>; }; interface Employee { name?: string | null; country?: string | null; salary?: number | null; } // 👇️ type T1 = { // name: string; // country: string; // salary: number; // } type T1 = WithoutNullableKeys<Employee>;
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.