Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Type Operators

TypeScript nullish coalescing (??)

Reference for the TypeScript ?? operator: defaults for null and undefined only, how it differs from ||, precedence rules and type results.

The nullish coalescing operator ?? returns its right operand only when the left operand is null or undefined. Otherwise it returns the left operand unchanged. It is the right tool for default values, because it keeps meaningful falsy values such as 0, "" and false.

TypeScript removes null and undefined from the left type in the result and unions it with the right type. For string | undefined ?? string the result is string.

TypeScript
function label(name: string | undefined): string {
  return name ?? "anonymous";
}

Try it

TypeScript ?? versus ||

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Types and chaining

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

TypeScript
left ?? right
Part Description
left Evaluated first. If it is neither null nor undefined, it is the result.
right Evaluated only when left is nullish (short-circuit).

Result type: NonNullable<typeof left> | typeof right.

Edge cases: NaN, 0, "" and false all count as present values, so they pass through. Mixing ?? with || or && without parentheses is a syntax error (a ?? b || c), so the intended grouping must be explicit.

Usage notes

  • Prefer ?? for defaults. value || fallback replaces every falsy value, which turns a legitimate 0 page number or empty string into the fallback.
  • Precedence is low. ?? binds more loosely than || and most arithmetic, so write (a ?? 0) + 1, not a ?? 0 + 1.
  • Works with optional chaining. user?.settings?.theme ?? "light" is the usual pattern; see optional chaining.
  • Assignment form: a ??= b assigns only when a is nullish; see logical assignment.
  • Unnecessary use: if the left side can never be nullish, the right side is dead code. Some lint rules report it.
  • Default parameters only react to undefined, not null, so ?? is useful inside functions to treat both the same.
  • Availability: since TypeScript 3.7.