My dev blog where I dive deep into TypeScript, Postgres, Data science, Infrastructure, Ethereum, and more...

Making nullable properties optional in TypeScript

20th May 2022

Sometimes optional properties turn out like nullable in the build system.

Let’s say you have a type like this:

type City = {
  name: string;
  population: number | null;
  mayor: string | null;
  dbId: string | null;
};

But you would like a type like this:

type City = {
  name: string;
  population?: number | null;
  mayor?: string | null;
  dbId?: string | null;
};

What we need is an OptionalNullable<T> type. This can be achieved by using a PickNullable and a PickNotNullable utility type and combining them together.

type PickNullable<T> = {
  [P in keyof T as null extends T[P] ? P : never]: T[P];
};

type PickNotNullable<T> = {
  [P in keyof T as null extends T[P] ? never : P]: T[P];
};

type OptionalNullable<T> = {
  [K in keyof PickNullable<T>]?: T[K];
} & {
  [K in keyof PickNotNullable<T>]: T[K];
};

// use it:
const city: OptionalNullable<City> = {
  name: "Los Angeles",
};

Thanks Tobias S for helping me on Stack Overflow.


Tools