CodePark/ questions / Generics
START PRACTICINGPRACTICE
Frontend question · TypeScript › Generics

Write a fully typed getProperty(obj, key) that only accepts existing keys and returns the right value type.

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:

  • keyof gives 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, T for the object and K for the key.
  • K extends keyof T allows only keys that exist on the object.
  • The return type T[K] is an indexed access type: the type of property K.
  • K is inferred as a literal like "name", so the result type is exact.