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

Constraining to Functions

Require generic parameters to be callable by constraining to function signatures.

Constraining to Functions

You'll learn how to require that a generic type parameter must be a callable function, ensuring type safety when working with higher-order functions.

The Problem: Accepting Any Type

When you write a generic function that needs to call its generic parameter, TypeScript won't let you invoke it unless you prove it's actually callable. Without constraints, a type parameter could be anything—a number, string, or object—none of which can be called like functions.

Using Function Signatures as Constraints

You can constrain a generic type parameter to be a function by using extends with a function type signature:

function callTwice<T extends () => void>(fn: T): void {
  fn();
  fn();
}

callTwice(() => console.log("Hello")); // ✓ Works
// callTwice(42); // ✗ Error: number is not a function

Here, T extends () => void means "T must be compatible with a function that takes no parameters and returns void."

Constraining to Functions with Parameters

You can require specific parameter and return types:

function mapArray<T extends (item: number) => any>(
  arr: number[],
  transform: T
): ReturnType<T>[] {
  return arr.map(transform);
}

const doubled = mapArray([1, 2, 3], x => x * 2); // number[]

The constraint T extends (item: number) => any ensures transform accepts numbers, while ReturnType<T> captures whatever the function actually returns.

Common Patterns

Use (...args: any[]) => any to accept any function while still preventing non-callable types:

function executeOnce<T extends (...args: any[]) => any>(fn: T): ReturnType<T> {
  return fn();
}

Key Takeaway: Constraining generic parameters to function signatures with extends lets you safely call them while preserving their specific types, enabling powerful higher-order function patterns.