← Back to TypeScript Course | Chapter 8: Advanced Types | Lesson 17 of 20

Utility Types - NonNullable

NonNullable<T> removes null and undefined from a type. It is useful when a value must be known to exist before it is used.

Basic NonNullable

NonNullable<T> removes null and undefined from a type T while preserving every other member of the union, narrowing a type that could be nullable into one that's guaranteed not to be.

Example: Basic NonNullable

typescript
type MaybeString = string | null | undefined;
type DefiniteString = NonNullable<MaybeString>;
const s: DefiniteString = "hello";
console.log(s);

NonNullable with Functions

NonNullable can clean up the return type of functions that may otherwise return null or undefined, which is useful once the caller has already handled or ruled out the nullable case.

Example: NonNullable with Functions

typescript
function findUser(id: number): string | undefined {
  return id === 1 ? "Ravi" : undefined;
}
type FoundUser = NonNullable<ReturnType<typeof findUser>>;
const name: FoundUser = "Ravi";
console.log(name);

NonNullable with Objects

NonNullable is useful when object properties or values can be null or undefined at the API boundary, but internal code wants a stricter, always-present type after validation has already ruled those cases out.

Example: NonNullable with Objects

typescript
interface ApiResponse {
  data: string | null;
}
type ValidatedData = NonNullable<ApiResponse["data"]>;
const data: ValidatedData = "payload";
console.log(data);

NonNullable with Unions

NonNullable can remove null and undefined from larger unions with several other members, retaining every other valid type in the union while stripping only the nullable parts, leaving the rest of the union exactly as it was.

Example: NonNullable with Unions

typescript
type Value = string | number | null | undefined;
type CleanValue = NonNullable<Value>;
const v: CleanValue = 42;
console.log(v);

When to Use NonNullable

Use NonNullable when a type represents a value that has already been checked for null or undefined elsewhere, so the rest of the code doesn't need to keep re-checking for it.

Example: When to Use NonNullable

typescript
function getLength(value: string | null): number {
  const checked: NonNullable<typeof value> = value ?? "";
  return checked.length;
}
console.log(getLength("hello"));

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.