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

Array Method Callbacks

Contextual typing in map, filter, reduce callbacks where parameter types come from the array element type.

Array Method Callbacks

You'll learn how TypeScript automatically infers parameter types in array method callbacks based on the array's element type.

How Contextual Typing Works in Array Methods

When you call methods like map, filter, or reduce on a typed array, TypeScript uses contextual typing to figure out what type each callback parameter should be. You don't have to annotate them manually—TypeScript knows what's in the array and applies that knowledge to your callback.

Think of it like a factory assembly line: if you have a conveyor belt of apples, anyone working on that line knows they'll receive apples, not oranges. Similarly, if you have an array of numbers, TypeScript knows your callback will receive numbers.

Examples

const numbers = [1, 2, 3, 4];

// TypeScript infers 'n' is number
const doubled = numbers.map(n => n * 2);

// TypeScript infers 'num' is number
const evens = numbers.filter(num => num % 2 === 0);

// TypeScript infers 'acc' and 'curr' are both number
const sum = numbers.reduce((acc, curr) => acc + curr, 0);

Notice you never wrote n: number or num: number—TypeScript figured it out from the array type.

Why This Matters

This automatic inference makes your code cleaner while keeping type safety. You get autocomplete on the parameters and TypeScript catches mistakes:

const words = ["hello", "world"];

// 'word' is inferred as string
words.map(word => word.toUpperCase()); // ✓ Works

words.map(word => word * 2); // ✗ Error: can't multiply string

Key Takeaway: TypeScript uses the array's element type to automatically infer callback parameter types in map, filter, reduce, and similar methods—you get safety without extra annotations.