Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: SetNonNullable #430

Closed
JohannCooper opened this issue Aug 5, 2022 · 0 comments · Fixed by #431
Closed

Proposal: SetNonNullable #430

JohannCooper opened this issue Aug 5, 2022 · 0 comments · Fixed by #431

Comments

@JohannCooper
Copy link
Contributor

JohannCooper commented Aug 5, 2022

Overview

Similar in syntax to the SetOptional and SetRequired types, SetNonNullable creates a type that makes the given keys non-nullable.

Example

type Foo = {
  a: number;
  b: string | undefined;
  c?: boolean | null;
}

type SomeNonNullable = SetNonNullable<Foo, 'b' | 'c'>;
// type SomeNonNullable = {
//   a: number;
//   b: string; // Can no longer be undefined.
//   c?: boolean; // Can no longer be null, but is still optional.
// }

Use Case

Most use cases that apply to the native NonNullable type apply here as well. The obvious difference is that SetNonNullable applies to types with keys. I have found this useful when storing form data within an object. After the form data has been validated to contain all required fields, it is useful to have a type to represent a valid, completed form.

For example,

type EmptyForm = {
  name: string | null;
  age: number | undefined;
};

type CompletedForm = SetNonNullable<EmptyForm, 'name' | 'age'>;

I personally try not to use null. However many forms are fetched from external sources where I cannot control the form structure. I often see a mix of undefined and null used to represented empty fields.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant