Yohohodev

Excluding null and undefined from object properties with TypeScript

#TypeScript

Here's a simple TypeScript code snippet that helps determine the type of an object while excluding null and undefined from all possible values of its properties.

type NonNullableProperties<T> = {
  [P in keyof T]: NonNullable<T[P]>;
};

What's going on here?

  1. keyof T - using the keyof operator to get the union of all keys of T.
  2. NonNullable<T[P]> - here we're utilizing the NonNullable utility type to exclude null and undefined from the type T[P]. This does not apply to optional properties. For those, you can use the -? syntax in the NonNullableProperties type, as shown below."
  3. [P in keyof T]: NonNullable<T[P]> is a mapped type that iterates over all the properties of T and replaces their types with NonNullable<T[P]>.

Here's an example of how to use it:

type ExampleType = {
  a?: string | null;
  b?: number | undefined;
  c: boolean | undefined | null;
  d: string;
};

type NonNullableExampleType = NonNullableProperties<ExampleType>;
// 👇
// { a?: string; b?: number; c: boolean; d: string }

If you want to remove optionaly properties from the type, you can use the Required utility type:

type RequiredExampleType = Required<ExampleType>;
// 👇
// { a: string; b: number; c: boolean; d: string }

or using -? syntax in NonNullableProperties:

type NonNullableProperties<T> = {
  [P in keyof T]-?: NonNullable<T[P]>;
};

type NonNullableExampleType = NonNullableProperties<ExampleType>;