sindresorhus / type-fest

A collection of essential TypeScript types
Creative Commons Zero v1.0 Universal
14.1k stars 533 forks source link

Proposal: NullToUndefined and UndefinedToNull #603

Open Xriuk opened 1 year ago

Xriuk commented 1 year ago

Recursively replace nullable properties with undefined/optional and viceversa:

type Nullable = {
  a: string;
  b: number | null;
}

type Undefineable = NullToUndefined<Nullable>;
/*{
  a: string;
  b: number | undefined;
}*/

This should also support nested types:

type ParentNullable = {
  a: boolean | null;
  b: {
    a: string;
    b: number | null;
  }
}

type ParentUndefineable = NullToUndefined<ParentNullable>;
/*{
  a: boolean | undefined;
  b: {
    a: string;
    b: number | undefined;
  }
}*/

Upvote & Fund

Fund with Polar

sindresorhus commented 1 year ago

What's the real-world use-case for this?

Xriuk commented 1 year ago

I'm using Angular and in their forms package each form control uses nulls instead of undefined, while my models use undefined (to mark optional properties), so I had the value of the form which was null-typed and didn't match the corresponding model:

interface Model{
  a: boolean;
  b?: string;
}

let modelFormGroup = new FormGroup({
  a: new FormControl(false, { nonNullable: true }), // boolean
  b: new FormControl("") // string | null
});
tkrotoff commented 1 year ago

I've implemented this proposal (types & the functions)

Source code including unit tests: https://gist.github.com/tkrotoff/a6baf96eb6b61b445a9142e5555511a0

tkrotoff commented 1 year ago

What's the real-world use-case for this?

Convert all null values from a REST API or a JSON file to undefined and vise versa because of https://github.com/sindresorhus/meta/discussions/7

Illustration: https://github.com/apollographql/apollo-client/issues/2412