Course contentsShow
← TypeScript
Lesson 544 of 1,79613. GenericsFree lesson

Generic Callback Parameters

Typing callbacks that use generic parameters from the outer function scope.

Generic Callback Parameters

What you'll learn: How to write callbacks that preserve and use generic type parameters from the function that contains them.

The Problem

When you write a function with generics, you often need to pass callbacks that work with those same generic types. The callback needs to "see" the type parameter from the outer function scope — otherwise, you lose all the type safety you worked to establish.

How It Works

Type parameters declared on a function are in scope for everything inside that function, including callback parameter types:

function map<T, U>(arr: T[], callback: (item: T) => U): U[] {
  const result: U[] = [];
  for (const item of arr) {
    result.push(callback(item));
  }
  return result;
}

const lengths = map(['a', 'bb', 'ccc'], str => str.length);
// lengths: number[]

Here, callback: (item: T) => U means the callback receives whatever type T is (inferred as string from the array) and returns type U (inferred as number from the return value).

Why This Matters

Without using the generic type parameters in your callback signature, you'd have to write callback: (item: any) => any, destroying type safety. By referencing T and U, the callback stays fully typed and TypeScript can infer both from usage.

Real Example

function filter<T>(arr: T[], predicate: (item: T) => boolean): T[] {
  const result: T[] = [];
  for (const item of arr) {
    if (predicate(item)) {
      result.push(item);
    }
  }
  return result;
}

const nums = filter([1, 2, 3, 4], n => n > 2);
// nums: number[], n is inferred as number

Key Takeaway: Generic type parameters from outer functions are accessible in callback type annotations, enabling type-safe callbacks that flow generic types through your logic.