NonNullable<T>
removes null and undefined from a type:
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