type-fest icon indicating copy to clipboard operation
type-fest copied to clipboard

Proposal: NullToUndefined and UndefinedToNull

Open Xriuk opened this issue 1 year ago • 4 comments

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

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

Xriuk avatar Apr 27 '23 09:04 Xriuk

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

sindresorhus avatar Apr 27 '23 19:04 sindresorhus

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
});

Xriuk avatar Apr 27 '23 19:04 Xriuk

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

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

tkrotoff avatar Jun 16 '23 20:06 tkrotoff

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

tkrotoff avatar Jun 16 '23 20:06 tkrotoff