Generic Constraints and keyof
A generic constraint limits which types may be used for a type parameter. T extends { id: string } means T must have at least that shape while retaining any additional properties. The keyof operator produces a union of property keys, and K extends keyof T ensures that a key is valid for the given object type.
This pattern is useful for property access helpers and reusable data utilities. The relationship between T and K is important: it allows the result type to be T[K], the actual type of the selected property.
Safe property accessor
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const product = { id: "p-1", price: 99, active: true };
const price = getProperty(product, "price"); // number
// getProperty(product, "missing"); // Error💡
K must be one of the keys of T, and the return type depends on the selected key. This prevents misspelled property names and retains the property's value type.Key Takeaways
- Use
extendsto constrain generic inputs. keyof Trepresents valid keys ofT.T[K]preserves the selected property's type.
Knowledge Check
What does `K extends keyof T` guarantee?