Skip to content

Commit

Permalink
Pass group keys as generics in array-group-by (#471)
Browse files Browse the repository at this point in the history
Co-authored-by: Thomas Clark <[email protected]>
  • Loading branch information
TClark1011 and Thomas Clark authored Jul 18, 2022
1 parent 0a79946 commit 37fcadc
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
5 changes: 4 additions & 1 deletion packages/array-group-by/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,7 @@
* @param arr the array to group
* @param resolver function used to resolve group key
*/
export default function groupBy<T>(arr: T[], resolver: (arg: T) => keyof any): Record<keyof any, T[]>
export default function groupBy<T, G extends keyof any = keyof any>(
arr: T[],
resolver: (arg: T) => G
): Record<G, T[]>;
29 changes: 22 additions & 7 deletions packages/array-group-by/index.tests.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,25 @@
import groupBy from './index'
import groupBy from "./index";

// OK
const test1: { [key: string]: number[] } = groupBy([6.1, 4.2, 6.3], Math.floor);
const test2: { [key: string]: string[] } = groupBy(['a', 'b', 'c', 'aa', 'bb', 'cc'], str => str.charAt(0));
const test3: { [key: string]: number[][] } = groupBy([[1], [2], [1, 2]], arr => arr.length);
const test2: { [key: string]: string[] } = groupBy(
["a", "b", "c", "aa", "bb", "cc"],
str => str.charAt(0)
);
const test3: { [key: string]: number[][] } = groupBy(
[[1], [2], [1, 2]],
arr => arr.length
);
const test4: {} = groupBy([], () => "a");
const test5: { [key: string]: Array<number | string>} = groupBy([1, 2, 3, "1", "2"], (a) => a);
const test6 = groupBy(['a', 'b', 'c'], str => Symbol(str));
const test5: { [key: string]: Array<number | string> } = groupBy(
[1, 2, 3, "1", "2"],
a => a
);
const test6 = groupBy(["a", "b", "c"], str => Symbol(str));
type K = "a" | "b";
const test7: Record<K, number[]> = groupBy([1, 2, 3], v =>
v % 2 === 0 ? "a" : "b"
);

// Not OK
// @ts-expect-error
Expand All @@ -16,7 +29,7 @@ groupBy();
// @ts-expect-error
groupBy({}, Math.floor);
// @ts-expect-error
groupBy('hello', Math.floor);
groupBy("hello", Math.floor);
// @ts-expect-error
groupBy(/hullo/, Math.floor);
// @ts-expect-error
Expand All @@ -25,7 +38,7 @@ groupBy(null, Math.floor);
groupBy(undefined, Math.floor);

// @ts-expect-error
groupBy(["a", "b", "c"], () => { });
groupBy(["a", "b", "c"], () => {});
// @ts-expect-error
groupBy(["a", "b", "c"], Math.floor);
// @ts-expect-error
Expand All @@ -42,3 +55,5 @@ groupBy([], null);
groupBy([], undefined);
// @ts-expect-error
groupBy([]);
// @ts-expect-error
groupBy<any, "good key">([], () => "bad key");

0 comments on commit 37fcadc

Please sign in to comment.