Interview Q&A / TypeScript

IntermediateQuick answer1 min readUpdated 3 Oct 2026

How do you write a type-safe getProperty function with keyof?

SHORT ANSWER

Use two type parameters: function getProperty<T, K extends keyof T>(obj: T, key: K): T[K]. K is limited to real keys of T, and the return type is exactly that property's type, so no casts or any are needed.

Explain it simply

A plain get(obj, key: string) can return anything and accept any key, including typos. You want the compiler to know that asking for "age" on a student returns a number.

The trick is to tie the two parameters together. K extends keyof T limits the key to valid ones, and the return type T[K] says "the type at that key". Each call then returns a precise type.

Example

ts
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const student = { name: "Asha", age: 20, passed: true };

const n = getProperty(student, "name");     // string
const a = getProperty(student, "age");      // number
console.log(n, a);                          // Asha 20
// getProperty(student, "marks");           // Error: not a key

function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
  return items.map(i => i[key]);
}
const ages = pluck([{ age: 20 }, { age: 22 }], "age");   // number[]

What to say in the interview

"I use <T, K extends keyof T> and return T[K]. K can only be a real key of the object, and the return type follows the chosen key, so every call is precise. It is the standard pattern for pluck, sort-by-field and form helpers."

Common mistakes

  • Typing key as string and returning any, which removes all safety.

#keyof#generics#indexed-access

Related questions

Practise more TypeScript questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open TypeScript quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.