Sequence NODE_177
Medium

Use keyof to Get Object Keys Type

TypeScript
Technical Specification

Create a function that takes an object and a key (restricted to the object's keys) and returns the value.

Input/Output Samples
Input:getProp(user, 'name')
Output:string
Optimal Logic Path
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
Architectural Deep-Dive
keyof and indexed access types let us enforce that only valid keys of an object can be used.