Struggling to figure out where I'm going wrong with this TypeScript signature after spending some time on it.
I've been working on a group by function:
const group = <T>(items: T[], fn: (item: T) => T[keyof T]) => {
return items.reduce((prev, next) => {
const prop = fn(next) as unknown as string;
return {
...prev,
[prop]: prev[prop] ? [...prev[prop], next] : [next],
};
}, {} as any);
};
group(data, (item) => item.type);
The current return type is:
const group: <Item>(items: Item[], fn: (item: Item) => string) => any
What I'm aiming for is:
const group: <Item>(items: Item[], fn: (item: Item) => string) => { admin: Item[], user: Item[] }
Here's the structure of the data:
interface User {
type: string;
name: string;
}
const data: User[] = [
{ type: 'admin', name: 'One' },
{ type: 'user', name: 'Two' },
{ type: 'admin', name: 'Three' },
];
I attempted this approach (with the object passed into reduce) but encountered an error and unsure about the solution:
{} as { [key: T[keyof T]: T[]] }
Check out the TS Playground link for the running code
Cheers!