How to Remove Null and Undefined from a Type in TypeScript?

Estimated read time 2 min read

In TypeScript, you can remove null and undefined from a type using the NonNullable utility type. Here’s an example:

interface Example {
  a: string | null | undefined;
  b?: number | null;
}

type NonNullableExample = {
  [K in keyof Example]: NonNullable<Example[K]>;
};

const example: NonNullableExample = {
  a: 'hello',
  b: 123
};

In this example, we have an interface called Example that has two properties a and b. a can be a string, null, or undefined, while b can be a number, null, or undefined.

We use the NonNullable utility type to create a new type called NonNullableExample that has the same properties as Example, but with null and undefined removed from their types.

We can then create an object of type NonNullableExample called example, which has a string value for a and a number value for b.

Note that this approach creates a new type with null and undefined removed from all properties. If you want to remove null and undefined from specific properties, you can use the Exclude utility type instead. Here’s an example:

interface Example {
  a: string | null | undefined;
  b?: number | null;
}

type ExampleWithoutNullAndUndefined = {
  [K in keyof Example]: Exclude<Example[K], null | undefined>;
};

const example: ExampleWithoutNullAndUndefined = {
  a: 'hello',
  b: 123
};

In this example, we use the Exclude utility type to create a new type called ExampleWithoutNullAndUndefined that has the same properties as Example, but with null and undefined removed only from their types.

We can then create an object of type ExampleWithoutNullAndUndefined called example, which has a string value for a and a number value for b.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply