Contextual Typing Not Applied Everywhere
What you'll learn: You'll discover where TypeScript's contextual typing works automatically and where it unexpectedly fails, forcing you to add explicit type annotations.
The Surprise Gap
You've seen contextual typing work beautifully with array method callbacks and event handlers—TypeScript magically knows what item is in items.map(item => ...) without you saying anything. But contextual typing has limits. It only flows "downward" from a known outer type to an inner expression. When you break that direct connection, the magic stops.
Where Context Breaks
Contextual typing works when TypeScript has an immediate expectation for a value's type. It fails when that connection is indirect:
Intermediate variables: If you extract a callback function into a variable before passing it, TypeScript loses context. The variable has no type expectation at the point of declaration, so parameters become any.
Standalone function declarations: Regular function declarations don't receive contextual hints—they exist independently. Only inline functions or variables with explicit type annotations get context.
Generic constraints without hints: When you use a generic function, TypeScript may not have enough information to infer the parameter types inside unless you provide explicit type arguments.
The key pattern: contextual typing requires an unbroken chain from a typed location to your expression. Any intermediate step without type information severs that chain.
Why This Matters
You might write what looks like identical code but get different inference results just by refactoring a callback into a variable. This feels inconsistent until you understand the rule: context flows directly, or not at all.
Key Takeaway: Contextual typing only applies when TypeScript has an immediate type expectation; extracting expressions into intermediate variables or standalone declarations breaks the context chain, requiring explicit annotations.