The use case is as follows
I have got
type A = {
a: number | undefined
b: string
}
// I want a helper type that will make so that the result is
type B = {
a: number| null
b: string
}
type A = {
a: number | null
b: string
}
// I want a helper type that will make so that the result is
type B = {
a: number| undefined
b: string
}
How can that be achieved. I have tried to find something online but I'm only getting javascript land stuff.
It should not add null, just replace the undefined with null.
And another helper type that is able to do the opposite ?
You can use a mapped type to map through all the properties and apply a conditional type that replaces undefined with null. You will also need to remove optionality from the properties (optionality implies a union with undefined)
type ReplaceUndefinedWithNull<T> = T extends undefined? null : T;
type ToNullProps<T> = {
[P in keyof T]-?: ReplaceUndefinedWithNull<T[P]>
}
To flip the types the other way we can create a similar type:
type ReplaceNullWithUndefined<T> = T extends null? undefined: T;
type ToUndefinedProps<T> = {
[P in keyof T]: ReplaceNullWithUndefined<T[P]>
}
Playground Link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With