04 / 08

What is contextual typing?

Difficulty: 5/10
type inference, function signatures, generic inference

Contextual typing is when TypeScript infers a type from the context/location where an expression appears — rather than from the expression itself. TypeScript looks at where something is used to figure out what type it should be.

javascript

Scenario Questions

0-2 years experience

  1. 1You have `const add = (a, b) => a + b;` and you assign it to a variable typed as `(x: number, y: number) => number`. What does TypeScript infer for the parameters, and why?
  2. 2If you write `let handler: (e: MouseEvent) => void = e => console.log(e.button);` and later call `handler({})`, what error appears and how does contextual typing cause it?

2-5 years experience

  1. 1We refactored a utility that maps over an array of objects using `array.map(item => ({ id: item.id, value: item.val }))`. After adding a type annotation to the array variable, the map callback's inferred type changed unexpectedly. Explain why and how you would fix it.
  2. 2A teammate added `function wrap<T>(value: T) { return { value }; }` and used `const result = wrap({ name: 'Bob' });`. Later they passed `result` to a function expecting `{ name: string; age: number }`. Why did TypeScript complain, and what role does contextual typing play?

5-8 years experience

  1. 1Our UI library uses many higher‑order components that rely on contextual typing for props inference. When we introduced a new optional prop, many components started failing type checks. Walk through how contextual typing interacts with default props and what strategies you’d use to mitigate the breakage.
  2. 2We are migrating a legacy JavaScript module to TypeScript and want to add minimal type annotations. How would you leverage contextual typing to get strong type safety without writing explicit interfaces for every function?

8+ years experience

  1. 1At the organization level we are standardizing a shared UI component library. Different teams consume components with varying prop shapes, and we rely on contextual typing to infer prop types from usage. Discuss the long‑term maintenance implications and how you’d design the library’s type exports to balance inference, explicitness, and compile‑time performance.
  2. 2When planning a monorepo migration from JavaScript to TypeScript across dozens of services, you propose using contextual typing as a primary strategy to reduce annotation overhead. What are the risks at scale, and how would you set up linting, build pipelines, and documentation to ensure type safety doesn't degrade over time?

Follow-up Questions

  • Can you illustrate that with a short code example?
  • What would change if you removed the surrounding type annotation?
  • When would you prefer an explicit type over contextual typing?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.