0Pricing
TypeScript Academy · Lesson

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

  1. Type Widening and Narrowing Mechanics
  2. Contextual Typing: Inference from Context
  3. Freshness and Excess Property Checking
  4. const Assertions and as const
← Back to TypeScript Academy