Questioning the TypeScript compiler's comprehension of my groupBy function, which includes an optional transformer for post-grouping data modification. Seeking suggestions on what steps to take next.
const customGrouping = <A extends {}, C, B extends keyof any>(
extractKey: (o: A) => B,
data: A[],
transformer?: (o: A) => C
) =>
data.reduce(
(acc, cur) => ({
...acc,
[extractKey(cur)]: (acc[extractKey(cur)] ?? []).concat(
transformer ? transformer(cur) : cur
),
}),
{} as Record<B, (A | C)[]>
)
// Implementation
const myList = [{ a: 1 }, { a: 2 }, { a: 3 }]
const result1 = customGrouping(
(x) => x.a,
myList,
)
//Actual type of result1: Record<number, unknown[]>
//Desired type of result1: Record<number, {a: number}[]>
const result2 = customGrouping(
(x) => x.a,
myList,
(x) => ({ b: x.a })
)
//Actual type of result2: Record<number, ({ a: number; } | { b: number; })[]>
//Desired type of result2: Record<number, {b: number}[]>