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.
- All episodes are in the TypeScript from Zero playlist.
- Versions used: Node.js 26.13.0, npm 11.20.0, TypeScript 7.0.2.
Setup
We start in the terminal and open the project in VS Code:
$ touch src/nulls.ts1. 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.
function find(id: number): string | null {
return id === 1 ? "Mia" : null;
}
console.log(find(1));
const found = find(2);
console.log(found);$ node src/nulls.ts2. 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.
console.log(found.length);$ node src/nulls.ts3. tsc
tsc sees it before we run: found is possibly null. The code is TS18047. TypeScript forces us to deal with the empty case.
$ npx tsc --noEmit4. 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.
$ node src/nulls.ts5. 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.
console.log(found ?? "nobody");$ node src/nulls.ts6. 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.
console.log(found!.length);$ npx tsc --noEmit7. Fix
We delete that line. The question mark and the double question mark are the safe tools.
$ npx tsc --noEmitRecap
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.