Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Concepts and Comparisons

null and undefined in TypeScript

How TypeScript treats null and undefined: strictNullChecks, optional values, ?? and ?., narrowing, and a clear convention for absence.

JavaScript has two "nothing" values. undefined is what the language gives you when something is missing: an uninitialized variable, an absent property, a function with no return. null is a value you put there on purpose to mean "no value".

With strictNullChecks on (part of strict), TypeScript treats both as separate types that are not part of string, number or object types. You must say string | null when absence is allowed, and the compiler then makes you handle it. This removes a large class of "cannot read properties of undefined" crashes.

TypeScript
let name: string | undefined;
// name.length;   // error TS18048: 'name' is possibly 'undefined'.

Try it

TypeScript Handling absence with ?? and ?.

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 Narrowing before use

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.

Practical differences

undefined null
Produced by The language (missing property, unset variable, no return) Code and APIs (JSON, DOM getElementById)
typeof "undefined" "object" (a historic quirk)
Default parameter applies Yes No
Dropped by JSON.stringify in objects Yes Kept as null
Loose equality undefined == null is true same

Usage notes

  • Use x == null only when you deliberately want to catch both; otherwise compare strictly. TypeScript narrows x == null to null | undefined in the true branch.
  • Optional (?) is not the same as | undefined. With exactOptionalPropertyTypes an optional property may be absent but not explicitly undefined; see exactOptionalPropertyTypes.
  • Non-null assertion ! removes both from the type without checking. Use it only where an invariant guarantees presence; see Non-null assertion.
  • Pick a convention. Many codebases use undefined for "not provided" and null only for external data that already uses it.
  • Arrays and maps: array[i] and record[key] are not undefined-aware unless you enable noUncheckedIndexedAccess; Map.get always includes undefined.
  • Without strictNullChecks, both values are assignable to every type, and the compiler cannot protect you.
  • Return types: a function that may find nothing should say so in its signature, such as T | undefined.