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

Parameter Inference in Callbacks

How TypeScript infers parameter types from contextual information in callback functions.

Parameter Inference in Callbacks

What you'll learn: How TypeScript automatically figures out callback parameter types without you writing them explicitly.

The Core Idea

When you pass a function as an argument (a callback), TypeScript already knows what that function should look like based on where you're using it. Instead of making you write out parameter types again, TypeScript infers them from the context—the type signature of the function that expects the callback.

Think of it like filling out a form: if the form says "Enter your age (number)," you don't need to write "number" next to your answer—the form already knows what type of data goes there.

How It Works

const numbers = [1, 2, 3];

// TypeScript infers 'num' is a number because map() expects a callback
// where the first parameter is the array element type
numbers.map(num => num * 2);
// num is inferred as: number

// Same with forEach
numbers.forEach(value => {
  console.log(value.toFixed(2)); // value is inferred as number
});

The map method has a type signature that says "I need a callback where the first parameter matches my array's element type." TypeScript reads that signature and automatically types your num parameter.

Why This Matters

You get full autocomplete and type safety without redundant annotations. TypeScript combines what it knows about the outer function with your callback to give you the right types automatically.

Key Takeaway: TypeScript infers callback parameter types from the expected function signature where the callback is used, giving you type safety without manual annotations.