Grass logo

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.

Hi!

I'm Lars. I write about building scalable systems, software architecture, and programming.

I created Turfemon to be my playground. A place where I can dive into technical topics, share quick insights, and document my learning journey, without contaminating my main site's pristine collection of 'profound' insights.

Working on something exciting? Send me an email: show email