capypad
0 day streak
typescript / intermediate
Snippet

Generics with keyof Constraints

Using 'keyof' with generics ensures that a function parameter is a valid key of a specific object, providing full type safety and IDE autocompletion.

snippet.ts
typescript
1
2
3
4
5
6
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
 
const user = { id: 1, name: "Bob" };
const userName = getProperty(user, "name");
Breakdown
1
K extends keyof T
Constraints the generic type K to only be keys that exist on type T.
2
obj[key]
TypeScript knows exactly what type the returned value will be based on the key used.