Problem Statement
Show how keyof + indexed access T[K] + Record build a flexible lookup API.
Explanation
keyof defines allowed keys, T[K] gives their value types, and Record<K, V> maps keys to values. Together they enforce key correctness and keep value types in sync—no stringly-typed lookups.
Code Solution
SolutionRead Only
type User = { id: string; active: boolean };
function pick<T, K extends keyof T>(obj: T, keys: K[]): Record<K, T[K]> {
const out = {} as Record<K, T[K]>;
for (const k of keys) out[k] = obj[k];
return out;
}
const u = { id: 'u1', active: true };
const subset = pick(u, ['id']); // { id: string }