M Logo
๐Ÿ“ TypeScript from Zero ยท Part 17 of 50

TypeScript null and undefined: Optional Chaining ?. , ?? and the ! Trap

November 6, 2026

Welcome to episode 17 of TypeScript from Zero, a series for complete beginners (no JavaScript needed). Welcome back to TypeScript from zero! Today: the value that means nothing. In many languages it causes the most crashes. We stay in the shop project, with a new file called nulls.ts. Every code block below is the code from the video, ready to copy; run each file to see the output.

Setup

We start in the terminal and open the project in VS Code:

bash
$ touch src/nulls.ts

1. Find

The function find returns a name, or null, which means: nothing found. Its return type says so: string or null. For the id one we get Mia. For the id two, we get null.

ts
function find(id: number): string | null {
  return id === 1 ? "Mia" : null;
}
console.log(find(1));
const found = find(2);
console.log(found);
bash
$ node src/nulls.ts

2. Crash

Now we ask for the length of the result. That is fine for Mia, but for null, Node crashes: cannot read properties of null. This is the most common error in real programs.

ts
console.log(found.length);
bash
$ node src/nulls.ts

3. tsc

tsc sees it before we run: found is possibly null. The code is TS18047. TypeScript forces us to deal with the empty case.

bash
$ npx tsc --noEmit

4. Optional chaining

The first tool: a question mark and a dot. If found is null, the whole expression simply gives undefined, instead of crashing. tsc is happy, and Node prints undefined.

bash
$ node src/nulls.ts

5. Nullish

The second tool: two question marks give a default value. If found is null or undefined, we get nobody instead. Note: a real empty text or a zero would stay as they are.

ts
console.log(found ?? "nobody");
bash
$ node src/nulls.ts

6. The ! trap

And a trap: an exclamation mark after a name tells TypeScript: trust me, this is not null. tsc goes quiet, but Node crashes again. We lied to the compiler, so it cannot protect us. Use it only when you are truly sure.

ts
console.log(found!.length);
bash
$ npx tsc --noEmit

7. Fix

We delete that line. The question mark and the double question mark are the safe tools.

bash
$ npx tsc --noEmit

Recap

Today: null in a union type, the crash it causes, optional chaining, the nullish default, and the exclamation mark trap. Next episode: literal types and as const.

ยฉ 2026 All Rights Reserved By Mahmudul Alam