3 min read
•Question 38 of 48easyWhat is the NonNullable utility type?
Removing null and undefined.
What You'll Learn
- NonNullable<T> usage
- Comparison with other approaches
- Practical examples
NonNullable<T>
Removes null and undefined from a type.
code.tsTypeScript
type MaybeString = string | null | undefined;
type DefiniteString = NonNullable<MaybeString>;
// stringExamples
code.tsTypeScript
type User = {
name: string;
email: string | null;
phone?: string;
};
type Email = NonNullable<User["email"]>;
// string
type Phone = NonNullable<User["phone"]>;
// stringWith Generics
code.tsTypeScript
function process<T>(value: T): NonNullable<T> {
if (value === null || value === undefined) {
throw new Error("Value required");
}
return value as NonNullable<T>;
}
const result = process("hello" as string | null);
// Type: stringImplementation
code.tsTypeScript
// How NonNullable works
type NonNullable<T> = T extends null | undefined ? never : T;Alternative Approach
code.tsTypeScript
// Using Exclude
type NonNull<T> = Exclude<T, null | undefined>;