typeof and Truthiness Narrowing
Use typeof checks to narrow primitive types.
Welcome
TypeScript narrows union types inside conditional blocks. `typeof` checks and truthiness checks are the most common narrowing techniques.
typeof Narrowing
Use `typeof` to check primitive types. TypeScript understands typeof checks and narrows the type inside the block.
function process(val: string | number) {
if (typeof val === 'string') {
return val.toUpperCase(); // val: string
}
return val.toFixed(2); // val: number
}All lessons in this course
- typeof and Truthiness Narrowing
- instanceof and in Narrowing
- User-Defined Type Guard Functions
- Exhaustiveness Checking with never