Using keyof in Generic Constraints
What you'll learn: How to constrain a generic type parameter with extends keyof T to ensure it represents only valid property names of another type.
The Core Idea
You've already seen that keyof extracts property names as a union type. Now you'll combine it with extends in generics to create a powerful constraint: forcing a type parameter to be one of the valid keys of another type parameter.
This pattern appears constantly when writing functions that access object properties dynamically, ensuring you can't accidentally reference keys that don't exist.
The Pattern: K extends keyof T
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"); // ✅ Type: string
const age = getProperty(person, "age"); // ✅ Type: number
const invalid = getProperty(person, "email"); // ❌ Error: "email" not in keyof person
Here, K extends keyof T means "K must be one of the keys of T." TypeScript infers both T (the object's shape) and K (the specific key you're accessing) from your arguments.
Why This Matters
Without this constraint, TypeScript can't verify that the key you're using actually exists on the object. The keyof constraint gives you:
- Compile-time safety when accessing properties
- Accurate return types (notice how the return type
T[K]reflects the actual property type) - Autocomplete for valid keys
Key Takeaway: Constraining a type parameter with extends keyof T ensures it can only be a valid property name from type T, enabling type-safe dynamic property access.