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
- GreenSnippets
- MIT
- Executed with Node.js 22 (type stripping)
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
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.
Related snippets
- JavaScript Tested
Remove duplicates from an array
Deduplicate primitives with a Set, or objects by a key or computed value, keeping the first occurrence.
- JavaScript Tested
Sort an array by multiple keys
Sort objects by one field, then break ties with another, with ascending or descending order per field.
- TypeScript Tested
Non-empty array type
Encode "at least one element" in the type so head, max and similar functions never see an empty array.
- PHP Tested
Group an array of records by a key
Turn a flat list of associative arrays into groups keyed by a field or callback.

