function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: 1, name: "Ann" };
const name = getProperty(user, "name"); // string
getProperty(user, "email"); // error
Use two type parameters: T for the object and K extends keyof T for the key. Return T[K].
T is the object type. K is limited with K extends keyof T, so it can only be one of the object's keys. Passing "email" is therefore a compile error.
The return type is the indexed access type T[K]. It means "the type of property K on T". TypeScript infers K as the literal "name", not as any key. So the result is string, not a union of every property type.
The three key ideas:
keyofgives the union of an object type's keys.- A constraint (
extends) ties one type parameter to another. - Indexed access (
T[K]) looks up the value type.
- The function uses two type parameters,
Tfor the object andKfor the key. K extends keyof Tallows only keys that exist on the object.- The return type
T[K]is an indexed access type: the type of propertyK. Kis inferred as a literal like"name", so the result type is exact.
Read more