diff --git a/test/groupBy.test.ts b/test/groupBy.test.ts new file mode 100644 index 0000000..64408cd --- /dev/null +++ b/test/groupBy.test.ts @@ -0,0 +1,29 @@ +import { expectType } from 'tsd'; +import { groupBy, __ } from '../es'; + +// returns optional arrays for the groups + +const byGrade = groupBy((student: { score: number; name: string }) => { + const score = student.score; + return score < 65 ? 'F' : score < 70 ? 'D' : score < 80 ? 'C' : score < 90 ? 'B' : 'A'; +}); +const students = [ + { name: 'Abby', score: 84 }, + { name: 'Eddy', score: 58 }, + { name: 'Jack', score: 69 } +]; + +const grouped = byGrade(students); +expectType<{ score: number; name: string }[] | undefined>(grouped.C); +(grouped.C ?? []).length; +// @ts-expect-error +grouped.C.length; + +// accepts a placeholder and later specifying the grouping function + +const byGrade2 = groupBy(__, students); +const grouped2 = byGrade2((student: { score: number; name: string }) => { + const score = student.score; + return score < 65 ? 'F' : score < 70 ? 'D' : score < 80 ? 'C' : score < 90 ? 'B' : 'A'; +}); +expectType<{ score: number; name: string }[] | undefined>(grouped2.C); diff --git a/types/groupBy.d.ts b/types/groupBy.d.ts index d688568..0c9b567 100644 --- a/types/groupBy.d.ts +++ b/types/groupBy.d.ts @@ -1,2 +1,5 @@ -export function groupBy(fn: (a: T) => K): (list: readonly T[]) => Record; -export function groupBy(fn: (a: T) => K, list: readonly T[]): Record; +import { Placeholder } from './util/tools'; + +export function groupBy(fn: (a: T) => K): (list: readonly T[]) => Partial>; +export function groupBy(__: Placeholder, list: readonly T[]): (fn: (a: T) => K) => Partial>; +export function groupBy(fn: (a: T) => K, list: readonly T[]): Partial>;