Inference Through Control Flow
You'll learn: How TypeScript automatically refines types as your code branches, loops, and reassigns variables.
The Core Idea
TypeScript doesn't just infer types once and forget about them. It actively tracks what's possible at every point in your code. When you write an if statement, a loop, or reassign a variable, TypeScript follows along and narrows or updates its understanding of what type a value could be.
Think of TypeScript as a detective walking through your code. At each if statement or assignment, it gathers clues: "Okay, if we're inside this branch, that variable can't be null anymore." It remembers this throughout the block.
How It Works in Practice
When you check a variable's type (like typeof x === "string"), TypeScript knows that inside the if block, x is definitely a string. You don't need to tell it again.
When you reassign a variable, TypeScript updates its inferred type based on the new value. If you start with let x = 10 (inferred as number), then later assign x = "hello", TypeScript adjusts to the broader type that allows both.
In loops, TypeScript tracks types iteration by iteration. If you filter or transform values, it follows the chain.
This is what makes TypeScript feel intelligent—it doesn't treat your entire function as one static snapshot. It understands the flow of execution.
Why This Matters
You write less redundant code. No need to cast or re-assert types after you've already checked them. TypeScript "remembers" your guards and branches, keeping autocomplete accurate and errors caught early—all without extra annotations.
Key Takeaway: TypeScript tracks and refines types as your code branches, loops, and reassigns—automatically narrowing possibilities based on the control flow path your code takes.