Lesson 4 of 7
Type Narrowing - How TypeScript Tracks Types
Type narrowing is TypeScript's process of refining a value's type within a conditional block. TypeScript tracks types through `typeof`, `instanceof`, `in`, equality checks, truthiness, and control flow. Understanding narrowing means you write fewer type assertions and more correct code.
All Narrowing Techniques
// ── typeof narrowing ─────────────────────────────────────────
function formatValue(value: string | number | boolean): string {
if (typeof value === "string") return value.toUpperCase();
if (typeof value === "number") return value.toFixed(2);
return value ? "Yes" : "No";
}
// ── instanceof narrowing ──────────────────────────────────────
function handleError(error: unknown): string {
if (error instanceof Error) return error.message;
if (typeof error === "string") return error;
return "Unknown error occurred";
}
// ── in narrowing - property existence ─────────────────────────
type Task = { kind: "task"; title: string; status: TaskStatus };
type Event = { kind: "event"; name: string; date: Date };
type Item = Task | Event;
function renderItem(item: Item): string {
if ("status" in item) {
return `Task: ${item.title} [${item.status}]`;
}
return `Event: ${item.name} on ${item.date.toDateString()}`;
}
// ── Equality narrowing ────────────────────────────────────────
function processStatus(status: TaskStatus | "unknown"): string {
if (status === "unknown") {
return "Status not available"; // narrowed to "unknown"
}
return status.toUpperCase(); // narrowed to TaskStatus
}
// ── Truthiness narrowing ──────────────────────────────────────
function getTitle(task: Task | null | undefined): string {
if (task) {
return task.title; // narrowed: task is Task (not null/undefined)
}
return "No task";
}
// ── Discriminant narrowing (from discriminated unions) ─────────
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rect"; width: number; height: number };
function area(s: Shape): number {
if (s.kind === "circle") return Math.PI * s.radius ** 2;
return s.width * s.height; // TypeScript knows it's rect here
}
// ── Control flow analysis - TypeScript tracks across branches ──
function process(value: string | null): string {
if (value === null) {
return "empty";
}
// TypeScript knows: value is string below this line
return value.toUpperCase(); // ✅ no need to check again
}
// ── Assignment narrowing ───────────────────────────────────────
let id: string | number = getRandomId();
id = 42;
id.toFixed(); // ✅ TypeScript knows id is number after this assignment
id = "abc";
id.toUpperCase(); // ✅ TypeScript knows id is string hereCommon Mistakes
- Using `as` instead of narrowing - `(value as string).toUpperCase()` bypasses the type system and can crash at runtime. Narrow with a condition instead.
- Using `typeof` to check for `null` - `typeof null` returns `'object'`, not `'null'`. Always use `value === null` for null checks.
- Underestimating control flow analysis - TypeScript tracks types through assignments, returns, and throws. Once a branch ends in a `return` or `throw`, TypeScript eliminates that type for the rest of the function.
Tip
Tip
Practice Type Narrowing How TypeScript Tracks Types in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Type Narrowing - How TypeScript Tracks Types
Practice Task
Note
Practice Task - (1) Write a working example of Type Narrowing How TypeScript Tracks Types from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Type Narrowing How TypeScript Tracks Types is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- Type narrowing is TypeScript's process of refining a value's type within a conditional block.
- Using `as` instead of narrowing - `(value as string).toUpperCase()` bypasses the type system and can crash at runtime. Narrow with a condition instead.
- Using `typeof` to check for `null` - `typeof null` returns `'object'`, not `'null'`. Always use `value === null` for null checks.
- Underestimating control flow analysis - TypeScript tracks types through assignments, returns, and throws. Once a branch ends in a `return` or `throw`, TypeScript eliminates that type for the rest of the function.
Finished this lesson?