#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
3 min read
Question 38 of 48easy

What 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>;
// string

Examples

code.tsTypeScript
type User = {
  name: string;
  email: string | null;
  phone?: string;
};

type Email = NonNullable<User["email"]>;
// string

type Phone = NonNullable<User["phone"]>;
// string

With 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: string

Implementation

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>;