Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a type where each nullable value becomes optional

I have a type like this one:

interface A {
  a: string
  b: string | null
}

I would like to generate the same type but each nullable value becomes optional:

interface A {
  a: string
  b?: string | null
}

Something like that but only for nullable values (this one makes all values optional):

export type NullValuesToOptional<T> = {
  [P in keyof T]?: T[P]
}
like image 499
Paleo Avatar asked Mar 26 '26 18:03

Paleo


1 Answers

Extracting the nullable field keys and then generating a new type based on that information would work.
This answer on removing never types holds the key to the puzzle.

interface A {
  a: string
  b: string | null
  c?: string | null;
  d?: string;
}

// Built-in NonNullable also catches undefined
type NonNull<T> = T extends null ? never : T;
type NullableKeys<T> = NonNullable<({
  [K in keyof T]: T[K] extends NonNull<T[K]> ? never : K
})[keyof T]>;

type NullValuesToOptional<T> = Omit<T, NullableKeys<T>> & Partial<Pick<T, NullableKeys<T>>>;

type B = NullValuesToOptional<A>;

Not as straight-forward as I'd have hoped, though.

like image 88
Etheryte Avatar answered Mar 29 '26 19:03

Etheryte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!