How do you write a type-safe getProperty function with keyof?
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
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.