Given all the answers already out there we tried to create a groupBy
arrow function that doesn't complain about TypeScript errors. with guidance from this answer and this one we already have this working code:
const groupBy = <TItem>(
items: TItem[],
key: string
): { [key: string]: TItem[] } =>
items.reduce(
(result, item) => ({
...result,
[item[key]]: [...(result[item[key]] || []), item],
}),
{}
)
It is indeed possible that the used key
is empty/blank. So TypeScript is not wrong here. So in that case it should simply use a placeholder value like NA
or something.
What is the correct way to create a reusable error free typescript version for this groupBy
function?