Constraining Multiple Type Parameters with keyof
You'll learn how to make one type parameter depend on another using keyof, enabling ultra-precise typing for functions that work with object keys and their corresponding values.
The Core Idea
Sometimes you need two related generic type parameters: one for an object type, and another for a valid key of that object. By constraining the second parameter with extends keyof, you create a type-safe relationship. When a third parameter needs to match the value type of that key, you can reference it with indexed access T[K].
This pattern appears frequently in object utilities, form handlers, and state management functions.
Plain English Explanation
Imagine a function that updates a property on an object. You want three guarantees:
- The object is some type
T - The key you're updating is actually on
T(that'sK extends keyof T) - The new value matches the type of that specific property (that's
T[K])
The keyof constraint chains these together, ensuring TypeScript knows that K is a real key of T, which lets you safely use T[K] to represent that property's value type.
Simple Pattern
function updateProperty<T, K extends keyof T>(
obj: T,
key: K,
value: T[K]
): void {
obj[key] = value;
}
const user = { name: "Alice", age: 30 };
updateProperty(user, "name", "Bob"); // ✓ Valid
updateProperty(user, "age", 25); // ✓ Valid
// updateProperty(user, "age", "25"); // ✗ Error: string not assignable to number
// updateProperty(user, "email", ""); // ✗ Error: "email" not a key of user
Key Takeaway: By constraining K extends keyof T and using T[K] for the value parameter, you create type relationships where one parameter's type depends on another's actual runtime value, achieving deep type safety across multiple generic parameters.