Skip to content
GreenSnippets

Type-safe pick and omit helpers for objects

Copy selected keys from an object (or drop some) with return types that match at compile time.

TypeScript
function pick<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Pick<T, K> {
  const out = {} as Pick<T, K>;
  for (const key of keys) {
    if (Object.hasOwn(obj, key)) out[key] = obj[key];
  }
  return out;
}

function omit<T extends object, K extends keyof T>(obj: T, keys: readonly K[]): Omit<T, K> {
  const drop = new Set<PropertyKey>(keys);
  const out: Partial<T> = {};
  for (const key of Reflect.ownKeys(obj) as (keyof T)[]) {
    if (!drop.has(key)) out[key] = obj[key];
  }
  return out as Omit<T, K>;
}

Example / expected output

Output
pick({ id: 1, name: "a", password: "x" }, ["id", "name"]) // { id: 1, name: "a" }

How it works

Pick and Omit exist as types; these are the matching runtime functions. The key arrays are constrained to keyof T, so a typo is a compile error. Only own enumerable keys are copied, and missing keys are skipped.