Multiple Type Parameters
You'll learn how to use more than one type parameter in a single generic, letting you handle functions that work with different types in different positions.
The Core Idea
So far, you've seen generics with a single type parameter like <T>. But what happens when a function needs to work with two or more different types that aren't related? For example, a function that pairs two values together, or one that transforms a value from one type to another?
That's where multiple type parameters come in. You can declare as many as you need, typically named <T, U>, <T, U, V>, and so on.
How It Works
When you declare multiple type parameters, each one can be independently inferred or specified. They work exactly like single type parameters, just with more flexibility.
Think of it like a vending machine with multiple slots: one slot accepts coins (type T), another accepts a selection code (type U), and it returns a snack (type V). Each slot has its own "type" but they all work together in one operation.
function pair<T, U>(first: T, second: U): [T, U] {
return [first, second];
}
const result = pair(42, "hello");
// result is [number, string]
const another = pair(true, { name: "Alice" });
// another is [boolean, { name: string }]
Each type parameter captures a different part of the operation, preserving type information independently.
When to Use Multiple Type Parameters
Use multiple type parameters when your function, interface, or class needs to work with genuinely different types in different positions—not just variations of the same type.
Key Takeaway: Multiple type parameters like <T, U> let you independently track different types within the same generic structure, giving you precise type safety when different arguments or return values have unrelated types.