null and undefined

Topic 2 of 5 in Unions and narrowing7 min readIntermediateFree course

Overview

Tony Hoare, who introduced null references in 1965, later called them his “billion-dollar mistake”. In JavaScript the most common crash of all is TypeError: Cannot read properties of undefined. TypeScript’s strict null checks remove that whole class of bug: they force you to deal with missing values before you use them.

Strict null checks

With strict on (the default since TypeScript 6), null and undefined are their own types and don’t fit anywhere else:

TypeScript
let name: string = "Asha";
name = null;
// error TS2322: Type 'null' is not assignable to type 'string'.

If something can be missing, the type must say so:

TypeScript
let nickname: string | undefined;     // not set yet
let manager: User | null = null;      // deliberately empty

undefined or null? JavaScript itself uses undefined for “missing” (absent properties, unreturned values, Array.find with no match). Many teams use undefined for everything and keep null only where an API requires it, such as JSON. Either works — be consistent.

Where possibly-missing values come from

TypeScript
const user = users.find((u) => u.id === 99);   // User | undefined
const first = names[0];                        // string | undefined (with noUncheckedIndexedAccess)
const el = document.querySelector(".menu");    // Element | null
const raw = process.env.PORT;                  // string | undefined
const map = new Map<string, number>();
map.get("tea");                                // number | undefined

TypeScript won’t let you use these as if they were definitely there:

TypeScript
console.log(user.name);
// error TS18048: 'user' is possibly 'undefined'.

Handling the missing case

Check with if

TypeScript
const user = users.find((u) => u.id === id);
if (user === undefined) {
  return "not found";
}
console.log(user.name);   // user: User from here on

An early return (or throw) leaves only the “present” case below it — a clean, common pattern. A truthiness check (if (!user)) also works for objects; be careful with strings and numbers, where "" and 0 are falsy but valid.

Optional chaining: ?.

Safe access with ?. and ??. In const city = user?.address?.city ?? “Unknown”;, if user is null or undefined the chain stops and gives undefined; if address is missing it stops and gives undefined; otherwise it reads city. Then ?? turns null or undefined into “Unknown”. ?. stops and gives undefined instead of throwing “Cannot read properties of undefined”. ?? supplies a fallback only for null or undefined — unlike ||, it keeps 0, “” and false. TypeScript knows city is string, because the fallback removes undefined from the type.

?. reads a property only if the thing before it isn’t null or undefined; otherwise the whole expression is undefined:

TypeScript
user?.address?.city          // string | undefined
user?.getRoles()             // call a method only if user exists
callback?.()                 // call a function only if it's defined
items?.[0]                   // index only if items exists

Nullish coalescing: ??

?? supplies a fallback when the left side is null or undefined:

TypeScript
const city = user?.address?.city ?? "Unknown";   // string
const port = Number(process.env.PORT ?? 3000);

Prefer ?? over || for defaults. || falls back for every falsy value:

TypeScript
const volume = settings.volume || 50;   // a volume of 0 becomes 50 — bug!
const volume = settings.volume ?? 50;   // 0 stays 0 ✓

??= assigns only if the variable is currently null or undefined: options.retries ??= 3.

Optional properties

An optional property (nickname?: string) is possibly undefined too, and needs the same handling:

TypeScript
type User = { name: string; nickname?: string };

function displayName(user: User): string {
  return user.nickname ?? user.name;
}

The non-null assertion: !

Putting ! after an expression tells TypeScript “this is definitely not null or undefined”:

TypeScript
const menu = document.querySelector(".menu")!;   // Element, no check

It removes the error, but checks nothing — if you’re wrong, you get the same run-time crash as in JavaScript. Use it only when you truly know better than the checker and the reason is obvious from the code next to it. Better alternatives:

TypeScript
const menu = document.querySelector(".menu");
if (!menu) throw new Error("Menu element is missing from the page");
menu.classList.add("open");   // checked, with a helpful error if the HTML changes

Narrowing survives… until it doesn’t

TypeScript tracks checks through your code, but it can’t know what happens inside a callback that runs later:

TypeScript
if (user.manager !== null) {
  setTimeout(() => {
    console.log(user.manager.name);
    // error TS18047: 'user.manager' is possibly 'null'.
  });
}

By the time the callback runs, user.manager could have changed. Copy the value into a const first: const manager = user.manager; if (manager) setTimeout(() => console.log(manager.name));.

The habit: every time TypeScript says “possibly undefined”, decide what should happen when it’s missing — return early, use a default with ??, or throw a clear error. That decision is the bug fix JavaScript never asked you to make.

Exercise

A safe user directory

Using the User type in the starter (some fields optional, manager may be null): (1) write findUser(id: number): User | undefined; (2) displayName(user: User): string — the nickname if set, otherwise the name; (3) managerName(user: User): string — the manager’s display name, or "no manager", using ?. and ??; (4) cityOf(id: number): string — the user’s address city, or "unknown", for any id (even one that doesn’t exist) in a single expression. Don’t use ! anywhere. Print results for ids 1, 2 and 99.

TypeScript
type User = {
  id: number;
  name: string;
  nickname?: string;
  address?: { city: string; country: string };
  manager: User | null;
};

const ravi: User = { id: 1, name: "Ravi Kumar", address: { city: "Pune", country: "IN" }, manager: null };
const asha: User = { id: 2, name: "Asha Rao", nickname: "Ash", manager: ravi };
const users: User[] = [ravi, asha];

// 1. findUser

// 2. displayName

// 3. managerName

// 4. cityOf

Summary

  • With strict null checks, null and undefined are separate types — a string can never be null.
  • Write T | undefined or T | null (or an optional ? property) when a value may be missing.
  • TypeScript makes you handle the missing case: check with if, or use ?. and ??.
  • ?? falls back only for null/undefined; || also replaces 0, "" and false.
  • The non-null assertion value! silences the check without checking anything — prefer a real check.