Refine primitive unions using runtime checks.
Section: Narrowing and Control Flow
Narrow with `typeof`
typescript
typescript
function printId(id: string | number) {
if (typeof id === "string") {
console.log(id.toUpperCase());
} else {
console.log(id.toFixed(0));
}
}Explanation
TypeScript uses control flow analysis to narrow `id` in each branch.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Narrowing and Control Flow
Narrow with `instanceof`
Refine class-based unions using constructor checks.
Narrow with the `in` operator
Refine unions by checking property existence.
Custom type guard with predicate
Teach TypeScript a reusable narrowing rule.
Type an async function
Return a typed promise from an async function.