Skip to content

Instantly share code, notes, and snippets.

@screfy
Last active March 2, 2022 19:26
Show Gist options
  • Save screfy/d54afebae25fca521c415c5c9558fc0d to your computer and use it in GitHub Desktop.
Save screfy/d54afebae25fca521c415c5c9558fc0d to your computer and use it in GitHub Desktop.
Pick key-value pair from an object in a type-safe fashion.
function pick<T, K extends Array<keyof T>>(
obj: T,
keys: K
): Pick<T, K[number]> {
return Object.fromEntries(
keys.filter((key) => key in obj).map((key) => [key, obj[key]])
) as Pick<T, K[number]>;
}
// Usage:
interface MyObject {
foo: string;
bar: string;
baz: number;
}
const myObj: MyObject = { foo: 'bar', bar: 'baz', baz: 1 };
const picked = pick(myObj, ['foo', 'baz']);
// { foo: string; baz: number }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment