Reverse Inference: From Usage to Definition
What you'll learn: How TypeScript can infer types backward by analyzing how you use a value later in your code.
The Core Idea
So far, you've seen TypeScript infer types based on what you assign to a variable — a number literal becomes number, an array becomes T[], and so on. But TypeScript is smarter than that: it can also look forward to see how you use a value and work backward to figure out what type it must be.
Think of it like a detective solving a mystery. If someone uses a key to unlock a door, the detective can infer: "That object must be a key." TypeScript does the same thing with your code.
How It Works
When TypeScript can't immediately determine a type (like with an empty array or a generic function), it examines later usage to narrow down possibilities:
// TypeScript sees an empty array — could be anything
const items = [];
// Now you push a number into it
items.push(42);
// TypeScript infers backward: items must be number[]
This also happens with function parameters in callback contexts:
const numbers = [1, 2, 3];
// TypeScript knows .map expects (value: number) => ...
numbers.map(n => n * 2);
// 'n' is inferred as number because of how numbers is used
TypeScript looks at what methods you call (.push(), .map()), what operations you perform, and what you pass values into — then works backward to figure out the most accurate type.
Why This Matters
Reverse inference reduces the need for explicit type annotations. You write less, but TypeScript still keeps you safe by understanding your intent through usage patterns.
Key Takeaway: TypeScript doesn't just infer types from initial values — it analyzes how you use values throughout your code and infers types backward from that context.