Narrowing: typeof instanceof discriminated unions
Use type guards to narrow union types at runtime with typeof, instanceof, and discriminated union patterns.
What Is Type Narrowing?
TypeScript starts with a wide type (e.g., string | number). Narrowing is the process of refining the type to a more specific one inside a conditional block. TypeScript tracks narrowing automatically.
typeof Narrowing
The typeof operator narrows primitives. Inside an if block, TypeScript knows the exact type.
function format(value: string | number | boolean): string {
if (typeof value === 'string') {
return value.toUpperCase(); // string here
}
if (typeof value === 'number') {
return value.toFixed(2); // number here
}
return String(value); // boolean here
}All lessons in this course
- Generics: T extends and constraints
- Utility Types: Partial Required Pick Omit
- Mapped Types and Conditional Types
- Narrowing: typeof instanceof discriminated unions