Keyof represents permitted keys; indexed access describes their value types. Linking a key parameter to its object avoids unrelated key and value combinations.
Before you start
You should be comfortable with JavaScript values, functions and objects. Use a TypeScript project with strict checking enabled when trying the examples. Separate what the compiler proves from what must still be checked when values arrive at runtime.
The practical goal is to reason through this situation: get<T, K extends keyof T>(obj: T, key: K): T[K] preserves the selected property’s type. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.
Step-by-step walkthrough
Step 1: Link the key to its object
A generic key must belong to the object’s known keys. A separate unconstrained string provides no such relationship.
Step 2: Preserve the selected value
Return T[K] so a numeric property remains numeric and a string property remains string. Returning a broad union loses useful information.
Step 3: Validate external key names
A query parameter is arbitrary text. Allow only explicitly supported names before passing it to the typed helper.
Worked scenario
get<T, K extends keyof T>(obj: T, key: K): T[K] preserves the selected property’s type.
function get<T, K extends keyof T>(object: T, key: K): T[K] {
return object[key];
}
const account = { name: 'Ada', attempts: 3 };
const attempts = get(account, 'attempts'); // number
const name = get(account, 'name'); // string
// get(account, 'password'); // rejected keyThis helper preserves a relationship already known to the compiler. It does not discover whether a user-provided string names a safe or authorized field.
Common mistake
A string from user input is not automatically a valid key.
Verify the behavior
Try each valid key and an invalid key. For an external field selector, test unsupported and sensitive names even if those fields exist on the runtime object.
Interview exercise
Read a dynamic key safely.
Answer and reasoning
Validate against supported keys before calling the typed helper; compile-time relationships do not authorize arbitrary input.
Continue learning
Compare the scenario with the TypeScript interview questions and test your understanding with the TypeScript MCQs. For terminology and implementation details, consult the reference material.