TypeScript Tutorial · TypeScript in Practice · Lesson 22 of 25

TypeScript Null Safety

strictNullChecks, optional chaining, nullish coalescing and noUncheckedIndexedAccess.

strictNullChecks

With strict on, null and undefined are separate types. A string can't be null unless you say string | null — and then you must handle it:

Example 1Try it yourself
function findUser(id: number): { name: string; manager?: { name: string } } | null {
  return id === 1 ? { name: "Ada", manager: { name: "Grace" } } : id === 2 ? { name: "Lin" } : null;
}

const u = findUser(3);
// console.log(u.name);   // ✗ compile error: 'u' is possibly 'null' (and a crash at runtime)
console.log(u?.name ?? "not found");
console.log(findUser(1)?.manager?.name, findUser(2)?.manager?.name ?? "no manager");

Output

not found
Grace no manager

Safe access

  • a?.b — undefined instead of crashing when a is null/undefined.
  • a ?? b — fall back only on null/undefined.

noUncheckedIndexedAccess

By default, arr[i] and record[key] are assumed to exist. The noUncheckedIndexedAccess option adds | undefined to such lookups, forcing you to handle missing items — recommended for new projects.

Example 2Try it yourself
const prices: Record<string, number> = { coffee: 3, tea: 2.5 };
const item = "cake";
const price = prices[item];             // number (or number | undefined with noUncheckedIndexedAccess)
console.log(price === undefined ? `${item} is not on the menu` : price.toFixed(2));

Output

cake is not on the menu

Test yourself

With strictNullChecks, can a variable of type string hold null?

  1. Yes
  2. No
Show answer

Answer: No