Advertisement
Advanced TypeScript, Generics

How would you write a generic 'pick' utility function that mimics the built-in Pick<T, K> utility type, but as a runtime function with matching compile-time types?

Short answer

Constrain K to `keyof T` (and typically require it to be an array of such keys), then build the result object at runtime while typing the return value as `Pick `, so the function's actual runtime behavior and its compile-time type both correctly narrow to just the requested keys.

Save TypeScript mock interview
Advertisement
AModel answer
Constrain K to `keyof T` (and typically require it to be an array of such keys), then build the result object at runtime while typing the return value as `Pick<T, K[number]>`, so the function's actual runtime behavior and its compile-time type both correctly narrow to just the requested keys.
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
  const result = {} as Pick<T, K>;
  keys.forEach(key => { result[key] = obj[key]; });
  return result;
}
const user = { name: 'Sam', age: 30, email: 'sam@x.com' };
const picked = pick(user, ['name', 'age']); // { name: string; age: number }
Real-world example
Implementing a fully type-safe runtime pick() helper matching lodash's behavior but with precise TypeScript inference.
Likely follow-ups
  • How does this differ from simply casting the result 'as any' and relying on the caller to trust the shape?
Related topics