← Back to TypeScript Course | Chapter 7: Generics | Lesson 7 of 8

Multiple Type Parameters

A generic declaration can use more than one type parameter when different values need separate types. Multiple parameters are useful for pairs, transformations, maps, and reusable data structures.

Two Type Parameters

Declare multiple type parameters separated by commas (like <T, U>) so each one can represent a different, independent type within the same generic function, class, or interface.

Example: Two Type Parameters

typescript
function pair<T, U>(first: T, second: U): [T, U] {
  return [first, second];
}
console.log(pair("id", 42));

Multiple Parameters in Functions

Separate type parameters can describe relationships between several arguments and the return type — for example, a merge function whose result type combines both input object types together.

Example: Multiple Parameters in Functions

typescript
function merge<T, U>(a: T, b: U): T & U {
  return { ...a, ...b };
}
console.log(merge({ name: "A" }, { age: 20 }));

Multiple Parameters with Transformations

Two type parameters are especially useful when a function transforms one type into another, such as mapping an array of T into an array of U using a supplied conversion function.

Example: Multiple Parameters with Transformations

typescript
function mapArray<T, U>(items: T[], fn: (item: T) => U): U[] {
  return items.map(fn);
}
console.log(mapArray([1, 2, 3], (n) => n.toString()));

Multiple Parameters in Interfaces

Interfaces can have multiple generic parameters when they describe relationships between distinct pieces of data, like a key type and a value type in a generic lookup or cache shape.

Example: Multiple Parameters in Interfaces

typescript
interface Cache<K, V> {
  get(key: K): V | undefined;
}
const cache: Cache<string, number> = {
  get: (key) => (key === "x" ? 1 : undefined),
};
console.log(cache.get("x"));

Multiple Parameters in Classes

Generic classes can use multiple type parameters to store values of genuinely different types together, such as a Pair<K, V> class holding one value of type K and another of type V.

Example: Multiple Parameters in Classes

typescript
class Pair<K, V> {
  constructor(public key: K, public value: V) {}
}
const pair = new Pair<string, number>("age", 30);
console.log(pair.key, pair.value);
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.