TypeScript Null & Undefined
The inventor of the null reference called it his "billion-dollar mistake". In JavaScript, Cannot read properties of undefined is probably the most common runtime error there is. TypeScript's answer is the strictNullChecks option (part of strict, and enabled in every playground on this site): null and undefined become separate types that are not part of string, number or any other type unless you say so.
Null is not a string
let nickname: string = "Bee";
nickname = null;
let maybeNickname: string | null = "Bee";
maybeNickname = null; // fine: null is in the unionmain.ts(2,1): error TS2322: Type 'null' is not assignable to type 'string'.
If a value may be missing, the type has to say so: string | null or string | undefined. Optional properties (email?: string) and optional parameters automatically include undefined.
Note: By convention,
undefinedmeans "not set / not there" (missing properties, uninitialised variables,Array.findwith no match) andnullmeans "deliberately empty". Many codebases pick one — usuallyundefined— and stick with it.
You must handle the missing case
Once a type includes undefined, TypeScript won't let you use the value as if it were always present:
const scores = [72, 95, 88];
const best = scores.find((s) => s > 90); // number | undefined
console.log(best.toFixed(1));main.ts(4,13): error TS18048: 'best' is possibly 'undefined'.
There are several ways to handle it.
Narrowing with a check
An if that rules out undefined narrows the type inside the block:
const scores = [72, 95, 88];
const best = scores.find((s) => s > 90);
const perfect = scores.find((s) => s === 100);
if (best !== undefined) {
console.log("best:", best.toFixed(1));
}
if (perfect === undefined) {
console.log("nobody scored 100");
}best: 95.0
nobody scored 100
Optional chaining ?. and nullish coalescing ??
Two JavaScript operators make this concise:
| Operator | Meaning |
|---|---|
a?.b |
if a is null/undefined, the result is undefined; otherwise a.b |
a?.() / a?.[i] |
same, for calls and index access |
a ?? b |
a, unless it is null/undefined, then b |
a ??= b |
assign b only if a is null/undefined |
interface Customer {
fullName: string;
address?: { city: string; zip?: string };
}
const c1: Customer = { fullName: "Thu", address: { city: "Hue" } };
const c2: Customer = { fullName: "Bao" };
console.log(c1.address?.city);
console.log(c2.address?.city);
console.log(c1.address?.zip ?? "no zip");
console.log(c2.address?.city ?? "unknown city");
let retries: number | undefined;
retries ??= 3;
console.log(retries);Hue
undefined
no zip
unknown city
3
Tip: Prefer
??over||for defaults.||also replaces0,""andfalse, socount || 10turns a real count of0into10;count ?? 10keeps the0.
The non-null assertion !
If you are certain a value is present, a postfix ! removes null | undefined from its type without any runtime check:
const env = new Map<string, string>([["MODE", "production"]]);
const mode = env.get("MODE")!;
console.log(mode.toUpperCase());
try {
const port = env.get("PORT")!; // compiles fine...
console.log(port.length);
} catch (err) {
console.log("runtime error:", (err as Error).name);
}PRODUCTION
runtime error: TypeError
The second block compiled without complaint, but port is really undefined, so port.length throws a TypeError (Cannot read properties of undefined) at runtime. ! silences the compiler; it doesn't make the value exist. Use it sparingly, and prefer a check or a default.
Test yourself
With strictNullChecks, can you assign null to a variable of type string?
- Yes, always
- No, the type must include
null, e.g.string | null - Only with
let - Only inside functions
What is 0 ?? 5?
- 5
- 0
- undefined
- false
What does user?.address?.city evaluate to when user is undefined?
- It throws a TypeError
- null
- undefined
- An empty string