Course contentsShow
← TypeScript
Lesson 182 of 1,7964. Type InferenceFree lesson

Callback Parameter Inference Gaps

When TypeScript can't infer callback parameter types and you must annotate them explicitly.

Callback Parameter Inference Gaps

You'll learn when TypeScript can't figure out your callback parameter types and you need to help it along.

The Problem

TypeScript is usually smart about inferring types in callbacks—especially when you pass them to well-typed functions like array.map() or array.filter(). But sometimes, the context isn't strong enough. When a function accepts a callback but doesn't provide enough type information about what that callback receives, TypeScript falls back to any for the parameters.

This happens most often with:

  • Custom functions that accept callbacks but aren't strongly typed
  • Generic utility functions without type constraints
  • Callbacks stored in variables before being passed
  • Libraries with incomplete or weak type definitions

Why It Happens

Think of contextual typing like a game of telephone. When you pass a callback directly to array.map(), TypeScript "hears" clearly what type each element is. But if that callback goes through a poorly-typed middleman function, the message gets garbled—TypeScript loses track of what the parameter should be.

What You Must Do

When this happens, you'll need to explicitly annotate the callback parameters yourself:

function processItems(callback) {  // weak typing here
  callback(42);
}

// TypeScript can't infer what 'x' is
processItems((x: number) => {  // must annotate!
  console.log(x.toFixed(2));
});

Without that : number, you'd get any (or an error if noImplicitAny is on).

Key Takeaway: When TypeScript can't infer callback parameter types from context—usually due to weak or missing types in the accepting function—you must annotate the parameters explicitly to maintain type safety.