TExcelTAD
Home › TypeScript › TS Null & Undefined

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

ts · try it yourself
let nickname: string = "Bee";
nickname = null;

let maybeNickname: string | null = "Bee";
maybeNickname = null;      // fine: null is in the union
main.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, undefined means "not set / not there" (missing properties, uninitialised variables, Array.find with no match) and null means "deliberately empty". Many codebases pick one — usually undefined — 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:

ts · try it yourself
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:

ts · try it yourself
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
ts · try it yourself
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 replaces 0, "" and false, so count || 10 turns a real count of 0 into 10; count ?? 10 keeps the 0.

The non-null assertion !

If you are certain a value is present, a postfix ! removes null | undefined from its type without any runtime check:

ts · try it yourself
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?

  1. Yes, always
  2. No, the type must include null, e.g. string | null
  3. Only with let
  4. Only inside functions

What is 0 ?? 5?

  1. 5
  2. 0
  3. undefined
  4. false

What does user?.address?.city evaluate to when user is undefined?

  1. It throws a TypeError
  2. null
  3. undefined
  4. An empty string