How do you use a generic type parameter to constrain a second parameter to be a valid key of the first?
Short answer
Use ` ` — this lets a function like a safe property-getter accept any key that ACTUALLY exists on T, catching typos or invalid keys at compile time, and lets the return type be precisely T[K].
Advertisement
AModel answer
Use `<T, K extends keyof T>` — this lets a function like a safe property-getter accept any key that ACTUALLY exists on T, catching typos or invalid keys at compile time, and lets the return type be precisely T[K].
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { name: 'Sam', age: 30 };
getProperty(user, 'name'); // OK, returns string
// getProperty(user, 'email'); // Error: 'email' is not a key of userReal-world example
Writing a fully type-safe generic getter/setter utility that catches invalid property names at compile time.
Likely follow-ups
- What does the resulting return type T[K] mean, and how is it different from just 'any'?
Related topics