typeof, equality, truthiness narrowing
Use typeof, strict equality, and truthiness to narrow union types without unsafe casts.
Intro
Goal: Narrow broad union types down to exact types using typeof, strict equality, and truthiness. This unlocks safe property/method access.
typeof narrowing
typeof narrows primitives (string, number, boolean, bigint, symbol, undefined). Use it to branch safely.
function printLen(x: string | number) {
if (typeof x === "string") {
console.log(x.length); // x is string
} else {
console.log(x.toFixed(2)); // x is number
}
}
printLen("TS");
printLen(3.14);All lessons in this course
- typeof, equality, truthiness narrowing
- in, instanceof, discriminated unions
- Exhaustiveness with never (intro)