Skip to content

Commit

Permalink
fix(pick): ensure pick satisfies Pick standard type
Browse files Browse the repository at this point in the history
  • Loading branch information
uladkasach committed Apr 24, 2024
1 parent 90552cc commit cc4fd3d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
10 changes: 10 additions & 0 deletions src/companions/pick.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { pick } from './pick';

describe('pick', () => {
it('should satisfy the standard Pick type', () => {
const withAll = { a: 1, b: 2 };

const pickKeyTypeFound = pick(withAll, ['a']);
const pickKeyTypeCheck: Pick<typeof withAll, 'a'> = pickKeyTypeFound;
});
});
9 changes: 6 additions & 3 deletions src/companions/pick.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
/**
* a companion to the `Pick` type, returns a new object with only the picked attributes
*/
export const pick = <T extends Record<string, any>>(
export const pick = <
T extends Record<string, any>,
K extends readonly (keyof T)[],
>(
obj: T,
keys: (keyof T)[],
): Pick<T, typeof keys[number]> =>
keys: K,
): Pick<T, K[number]> =>
Object.entries(obj).reduce((summary, [key, value]) => {
// if key is not in the specified keys, dont add it to the new object
if (!keys.includes(key)) return summary;
Expand Down

0 comments on commit cc4fd3d

Please sign in to comment.