type-fest
type-fest copied to clipboard
Proposal: `SetNonNullable`
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.