Combining keyof with Conditional Constraints
What you'll learn: How to create generic constraints that depend on both property keys (keyof) and conditional logic to enforce type-safe relationships between parameters.
The Core Idea
Sometimes you need a generic function where the allowed values for one type parameter depend on both what keys exist on another type and what type those properties hold. This is where conditional constraints with keyof shine—you can say "T must be a key of O, but only if O[T] meets certain conditions."
Think of it like a smart filter on a key ring: instead of just checking "is this a valid key?", you're checking "is this a valid key and does it unlock the right kind of door?"
Basic Pattern
function updateNumeric<O, K extends keyof O & (O[K] extends number ? K : never)>(
obj: O,
key: K,
increment: number
): void {
(obj[key] as number) += increment;
}
const stats = { score: 100, name: "Alice" };
updateNumeric(stats, "score", 10); // ✓ Works
updateNumeric(stats, "name", 10); // ✗ Error: "name" doesn't point to number
Here, K must be a key of O, but the conditional O[K] extends number ? K : never filters out keys whose values aren't numbers.
Why This Matters
This technique prevents runtime type errors by encoding complex business rules at compile time. You're not just saying "any key works"—you're saying "only keys that point to the right kind of value."
Key Takeaway: Combining keyof with conditional constraints lets you filter generic type parameters based on property value types, creating highly precise and safe APIs that enforce relationships between object shapes and their keys.