Skip to content

Commit

Permalink
Use generic for Record key type
Browse files Browse the repository at this point in the history
This lets the function pass through more specific type information
  • Loading branch information
Zanchi committed Apr 22, 2022
1 parent 3fd356a commit b3fac98
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
8 changes: 4 additions & 4 deletions packages/object-map/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
declare function map<T, U = T>(
item: Record<string, T>,
callback: (key: string, value: T) => U
): Record<string, U>;
declare function map<K extends string | number | symbol, T, U = T>(
item: Record<K, T>,
callback: (key: K, value: T) => U
): Record<K, U>

export default map;
8 changes: 7 additions & 1 deletion packages/object-map/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,16 @@ const test3: Record<string, string> = map(
{ a: "pple" },
(key, value) => key + value
);
type MyObject = {
k1: number,
k2: number,
}
const myObject: MyObject = { k1: 1, k2: 2 };
const test4: MyObject = map(myObject, (key: keyof MyObject, value) => value + 1);

// Not OK
// @ts-expect-error
const test4: Record<string, string> = map({ foo: 1 }, (_, value) => value + 1);
const test5: Record<string, string> = map({ foo: 1 }, (_, value) => value + 1);
// @ts-expect-error
map();
// @ts-expect-error
Expand Down

0 comments on commit b3fac98

Please sign in to comment.