NonNullable<T> removes null and undefined from a type. NonNullable<string | null | undefined> is just string, which is the type a value has after a null check.
type MaybeString = string | null | undefined;
type DefinitelyString = NonNullable<MaybeString>; // string
function processValue(value: string | null | undefined): void {
if (value !== null && value !== undefined) {
// Type narrowing
const processed: NonNullable<typeof value> = value; // string
console.log(processed.toUpperCase());
}
}
// Useful with arrays
type ArrayItem<T> = T extends (infer U)[] ? NonNullable<U> : never;
type StringArrayItem = ArrayItem<(string | null)[]>; // string
For a union, it drops the null and undefined members and keeps the rest. Inside a function, NonNullable<typeof value> names the narrowed type of a parameter. The last two lines use it inside a conditional type to clean up an array's element type.
It changes only the type, never the value. To remove nulls from data you still need a runtime check, and NonNullable then describes what is left.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓