null and undefined
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:
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:
let nickname: string | undefined; // not set yet
let manager: User | null = null; // deliberately emptyundefined 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
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 | undefinedTypeScript won’t let you use these as if they were definitely there:
console.log(user.name);
// error TS18048: 'user' is possibly 'undefined'.Handling the missing case
Check with if
const user = users.find((u) => u.id === id);
if (user === undefined) {
return "not found";
}
console.log(user.name); // user: User from here onAn 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: ?.
?. reads a property only if the thing before it isn’t null or undefined; otherwise the whole expression is undefined:
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 existsNullish coalescing: ??
?? supplies a fallback when the left side is null or undefined:
const city = user?.address?.city ?? "Unknown"; // string
const port = Number(process.env.PORT ?? 3000);Prefer ?? over || for defaults. || falls back for every falsy value:
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:
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”:
const menu = document.querySelector(".menu")!; // Element, no checkIt 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:
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 changesNarrowing survives… until it doesn’t
TypeScript tracks checks through your code, but it can’t know what happens inside a callback that runs later:
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.
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.
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. cityOftype 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
function findUser(id: number): User | undefined {
return users.find((user) => user.id === id);
}
// 2. displayName
function displayName(user: User): string {
return user.nickname ?? user.name;
}
// 3. managerName
function managerName(user: User): string {
return user.manager ? displayName(user.manager) : "no manager";
}
// 4. cityOf
function cityOf(id: number): string {
return findUser(id)?.address?.city ?? "unknown";
}
for (const id of [1, 2, 99]) {
const user = findUser(id);
if (user === undefined) {
console.log(`#${id}: not found, city ${cityOf(id)}`);
continue;
}
console.log(`#${id}: ${displayName(user)}, manager: ${managerName(user)}, city: ${cityOf(id)}`);
}Summary
- With strict null checks,
nullandundefinedare separate types — astringcan never benull. - Write
T | undefinedorT | 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 fornull/undefined;||also replaces0,""andfalse.- The non-null assertion
value!silences the check without checking anything — prefer a real check.