Skip to content

QuizNot attempted

Generic constraints

Why does this error, and what is the fix?
function getProp<T>(obj: T, key: string) {
return obj[key]; // error
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • key could be any string; use <T, K extends keyof T>(obj: T, key: K): T[K]
  • key: string could be any string, so obj[key] is not known to exist on T
  • constraining K extends keyof T makes the access safe and gives a precise T[K] return type.
  • Not 'use any': generics can index objects once constrained, and any discards safety.
  • Not 'declare as object': object has no known keys either.
  • Not obj.key: that reads a literal property named key.