Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript replace null with undefined type

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading