Nullable Unions

Model values that might be missing with a union including null or undefined.

Syntaxlet name: string | undefined;

Combine a type with null or undefined to model optional data. A common pattern is string | null for a value that may be absent.

TypeScript then forces you to handle the empty case before using the value, preventing null-related crashes.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A database findById method returns User | null, forcing callers to check for null before reading properties.
  • A form field value is typed string | undefined to represent a field that the user may not have filled in.
  • An optional API parameter is typed number | null to distinguish between not provided and explicitly cleared.

More examples

Return null for not found

Returns null when a lookup fails and uses a null check to guard property access at the call site.

Example · ts
function findItem(id: number): { label: string } | null {
  const store: Record<number, { label: string }> = { 1: { label: 'Item A' } };
  return store[id] ?? null;
}

const item = findItem(2);
if (item !== null) {
  console.log(item.label);
}

Optional chaining with nullable

Uses optional chaining (?.) and nullish coalescing (??) to safely navigate a potentially null nested object.

Example · ts
interface Profile {
  user: { name: string } | null;
}

function getDisplayName(profile: Profile): string {
  return profile.user?.name ?? 'Anonymous';
}

Non-null assertion operator

Shows the ! non-null assertion and contrasts it with a safer explicit null guard to highlight when each is appropriate.

Example · ts
function getLength(text: string | null): number {
  // Use ! only when you are certain value is not null
  return text!.length;
}

// Better: use a guard instead
function safeLengthOf(text: string | null): number {
  if (text === null) return 0;
  return text.length;
}

Discussion

  • Be the first to comment on this lesson.