I am working on a function called groupBy
, but the type system is giving me some trouble.
export function group<
T extends object,
K extends (keyof T & string),
R = T[K] extends string ? string : never
>(
data: T[],
groupBy: keyof T
): { [group: R]: T[] }
One of the errors I encountered is that R
in { [group: R]: T[] }
needs to be either string
or number
.
This signature does not work properly for datasets like:
group([{ name: 'Johnny Appleseed', age: 17 }], 'name') // R should be string
group([{ name: 'Johnny Appleseed', age: 17 }], 'age') // R should be never
In these cases, R
becomes never
while K
is "name" | "age"
To fix this, I have to manually specify the type parameters using
group<{name: string, age: number}, 'name'>
to ensure that R
is string
.