Multiple Type Parameters with Constraints
What You'll Learn
You'll learn how to coordinate constraints across multiple generic parameters where one type parameter depends on another.
Why This Matters
Sometimes you need two (or more) type parameters in a function, but they're not independent—one needs to be related to the other. For example, you might have a parameter T representing an object, and another parameter K that must be a valid key of T. Without constraints, TypeScript can't guarantee this relationship.
Coordinating Multiple Type Parameters
When you have multiple type parameters, you can constrain later ones based on earlier ones:
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const person = { name: "Alice", age: 30 };
const name = getProperty(person, "name"); // string
const age = getProperty(person, "age"); // number
// Error: Argument of type '"email"' is not assignable to parameter of type '"name" | "age"'
// getProperty(person, "email");
Here, K is constrained to keyof T, meaning K must be a valid property name of whatever T is. The second parameter depends on the first.
The Dependency Chain
Think of it like a lock and key: parameter T defines what the lock looks like, and parameter K must be a key that fits that specific lock. TypeScript ensures they work together.
You can even chain constraints further:
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
// Implementation would return subset of obj
}
Key Takeaway: When one generic type parameter needs to relate to another, use extends to create constraints that reference earlier type parameters, ensuring they work together safely.