Parameter Type Inference from Context
What you'll learn: How TypeScript automatically figures out parameter types when you write callback functions and event handlers.
When you pass a function as an argument to another function (like in array methods or event listeners), TypeScript can infer the types of your callback's parameters based on what the outer function expects. You don't have to write the types yourself—TypeScript looks at the context where your function is being used.
Why Context Matters
Think of it like a job interview: if you're applying to be a chef, the interviewer expects you to know about cooking. They don't need to explain what "sauté" means—the context (a chef interview) tells them you should already know.
Similarly, when you write a callback for Array.map(), TypeScript knows what type of elements are in the array, so it automatically types your callback's parameters.
How It Works
When you write:
const numbers = [1, 2, 3];
numbers.map(n => n * 2);
TypeScript contextually infers that n is number because numbers is an array of numbers. You didn't write n: number, but TypeScript figured it out from where the callback is used.
The same happens with event handlers:
button.addEventListener('click', event => {
// event is automatically MouseEvent
});
TypeScript knows addEventListener expects a function that receives a specific event type, so it infers event appropriately.
When Context Helps
This inference works when:
- Your function is passed directly as an argument
- The receiving function has known parameter types
- You're using built-in methods or well-typed libraries
Key Takeaway: TypeScript automatically infers parameter types for callbacks and handlers by looking at the context where they're used, saving you from writing redundant type annotations.