Home > Mobile >  How to make nullable properties optional in TypeScript?
How to make nullable properties optional in TypeScript?

Time:05-09

I have a type like this:

type City = {
  name: string;
  id: number | null;
};

And want to turn it into a type like this:

type City = {
  name: string;
  id?: number;
};

I have seen plenty of posts explaining how to make optional types nullable, but I want the opposite here.

Is there any way to create a TypeScript generic function like OptionalNullable<T> that handles this?

CodePudding user response:

This should do the trick:

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>]?: Exclude<T[K], null>
} & {
  [K in keyof PickNotNullable<T>]: T[K]
}

I created two utility types which pick all nullable not non-nullable properties from a type respectively. We can use these to construct a new type where all nullable properties are made optional. I also used Exclude so to get rid of null.

It can be used like this:

type City = {
  name: string;
  id: number | null;
};

type Test = OptionalNullable<City>
// {
//    id?: number | undefined;
// } & {
//     name: string;
// }

Playground

CodePudding user response:

You could always write something like this assuming that you only want to change a set amount of keys in the object

type City = {
  name: string;
  id: number | null;
};

type CityCorrect = Omit<City, "id"> & {
    id?: string
} 

// CityCorrect will now have the type
/* 
type CityCorrect {
    name: string
    id?: number
}
*/
  • Related