'How to make nullable properties optional in TypeScript?
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?
Solution 1:[1]
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;
// }
Solution 2:[2]
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
}
*/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Hampfh |
