Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 621
Renan Cidale Avatar asked Oct 28 '25 17:10

Renan Cidale


1 Answers

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

like image 142
Titian Cernicova-Dragomir Avatar answered Oct 31 '25 05:10

Titian Cernicova-Dragomir