How would you write a generic 'NonNullable' utility to strip null and undefined from a type, and how does the built-in version work?
Short answer
The built-in NonNullable is implemented as a conditional type: `type NonNullable = T extends null | undefined ? never : T;` — since it's a distributive conditional type, applying it to a union automatically removes just the null/undefined members while preserving everything else.
Advertisement
AModel answer
The built-in NonNullable<T> is implemented as a conditional type: `type NonNullable<T> = T extends null | undefined ? never : T;` — since it's a distributive conditional type, applying it to a union automatically removes just the null/undefined members while preserving everything else.
type NonNullable<T> = T extends null | undefined ? never : T;
type A = NonNullable<string | null | undefined>; // string
type B = NonNullable<number | null>; // numberReal-world example
Deriving a 'safe' version of a type after establishing (via runtime checks) that a value can no longer be null/undefined in a given code path.
Likely follow-ups
- How does this rely on the distributive behavior of conditional types over a union, specifically?
Related topics