Contextual Typing: Inference from Context
Understand how TypeScript infers types from surrounding context.
What Is Contextual Typing?
Contextual typing occurs when TypeScript infers the type of an expression based on the position it appears in — the context provides the type, not the value itself.
document.addEventListener("click", (e) => {
// e is inferred as MouseEvent from the event type
console.log(e.clientX);
});Contextual Typing in Callbacks
When you pass a callback to a typed function, TypeScript infers parameter types from the expected callback signature.
const nums = [1, 2, 3];
nums.forEach((n) => {
// n inferred as number from Array<number>
console.log(n.toFixed(2));
});All lessons in this course
- Type Widening and Narrowing Mechanics
- Contextual Typing: Inference from Context
- Freshness and Excess Property Checking
- const Assertions and as const