Issue
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
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;
// }
Answered By - Tobias S.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.