Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Primitive and Special Types

The TypeScript null type

Reference for null in TypeScript: the null type, strictNullChecks, narrowing with === null, ?? and ?., null versus undefined and common API patterns.

null is a value that means "deliberately no value", and null is also the name of its type. With strictNullChecks on (part of strict, and the default in modern projects) null is not assignable to other types, so a variable that may hold it has to say so with a union such as string | null.

The compiler then forces you to handle the empty case before using the value. This removes the classic "cannot read properties of null" crash from the type checker's point of view.

TypeScript
let name: string | null = null;
name = "Ada";

Try it

TypeScript Narrowing away null

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 null in real APIs

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
let a: null = null;
let b: string | null = null;
function f(x: number | null): void { /* ... */ }
Form Description
null (type) Contains only the value null.
T | null A value that may be missing.
x === null Precise check that narrows T | null to T.
x == null Matches both null and undefined.
x! Non-null assertion; removes null and undefined without a runtime check.

Usage notes

  • typeof null is "object". This is an old JavaScript quirk. Compare with === null instead of using typeof.
  • Without strictNullChecks, null is assignable to everything and the type is effectively invisible. Always enable it.
  • Prefer one empty value. Many codebases use undefined for "not provided" and reserve null for "explicitly empty" (databases, JSON, DOM APIs). Mixing both in one type (T | null | undefined) invites bugs.
  • Operators. ?? replaces null and undefined only, unlike || which also replaces 0 and "". ?. stops at either.
  • JSON round trips. null survives JSON.stringify; undefined properties are dropped.
  • Filtering. .filter(Boolean) does not change the array type; use a type predicate as above.
  • DOM. document.querySelector returns Element | null; check or assert before use.
  • Error messages. Possible null reads report TS18047 ("'x' is possibly 'null'").