Typing Anonymous Functions
You'll learn how TypeScript infers types for inline anonymous functions based on context, and when you need to add annotations yourself.
Understanding Contextual Typing for Anonymous Functions
When you pass an anonymous function (like an arrow function or function expression) directly into another function, TypeScript often knows what types the parameters should have without you writing them. This is called contextual typing — the function's context (where it's used) tells TypeScript what types to expect.
For example, when you pass a callback to Array.filter(), TypeScript already knows from the method signature that your callback receives an element of the array type. You don't need to annotate the parameter:
const numbers = [1, 2, 3, 4, 5];
// ✅ TypeScript infers 'n' is number
const evens = numbers.filter(n => n % 2 === 0);
Here, n is automatically typed as number because TypeScript knows filter expects a callback that receives array elements.
When Contextual Typing Fails
If you assign the anonymous function to a variable first, or use it in a place where TypeScript can't determine the expected signature, you'll need to annotate parameters explicitly:
// ❌ Error: Parameter 'n' implicitly has 'any' type
const isEven = n => n % 2 === 0;
// ✅ Fixed with annotation
const isEven = (n: number) => n % 2 === 0;
Without context, TypeScript doesn't know what n should be.
Key Takeaway: Inline anonymous functions often get their parameter types automatically from context, but when assigned to variables or used outside clear contexts, you must annotate them explicitly.