What Is Contextual Typing
You'll learn how TypeScript infers types based on where a value is used, not just the value itself.
The Core Idea
So far, you've seen TypeScript infer types from the value you write—like inferring number from 42. But TypeScript also works backwards: it looks at where you're using a value and infers types from that context.
Think of it like filling in a form. If a field is labeled "Date of Birth," you know what kind of information to write—even before you start typing. TypeScript does the same: it sees the "label" (the expected type) and helps you fill it in correctly.
Context Provides Type Information
When you assign a function to a typed variable, pass a callback to a method, or return a value from a typed function, TypeScript uses the expected type to infer parameter types and return types.
This is contextual typing: the surrounding code provides type context, so you don't have to annotate everything manually.
A Simple Analogy
Imagine you're handing someone a tool. If they're holding a toolbox labeled "screwdrivers only," you know what to give them. TypeScript's contextual typing works the same way: the "box" (expected type) tells TypeScript what kind of value belongs there.
When It Happens
Contextual typing occurs in:
- Callback functions (like in array methods you've seen)
- Event handlers
- Function assignments
- Object literals assigned to typed variables
TypeScript combines what it knows from the value and the context to give you the most precise type.
Key Takeaway: Contextual typing infers types by looking at where a value is used, not just what the value is—reducing the need for manual annotations.