I am trying to add types to function that takes array of objects and groups them by key.
Here is my code:
interface ITask {
assignedTo: string;
tasks: Array<string>,
date: string;
userId: number;
};
interface IFormattedOutput<T> {
[prop: string]: Array<T>;
}
const testData: Array<ITask> = [
{
assignedTo: 'John Doe',
tasks:['Code refactoring', 'Demo', 'daily'],
date: '1-12-2022',
userId: 123
},
{
assignedTo: 'Maximillian Shwartz',
tasks:['Onboarding','daily'],
date: '1-12-2022',
userId: 222
},
{
assignedTo: 'John Doe',
tasks:['Team Menthoring', 'daily', 'technical call'],
date: '1-13-2022',
userId: 123
},
{
assignedTo: 'John Doe',
tasks:['New dev onboardin','daily'],
date: '1-12-2022',
userId: 123
}
]
const groupByKey = <T, K extends keyof T>(list: Array<T>, key: K):IFormattedOutput<T> => {
return list.reduce((reducer, x) => {
(reducer[x[key]] = reducer[x[key]] || []).push(x);
return reducer;
}, {});
};
const res = groupByKey <ITask, 'assignedTo'>(testData, 'assignedTo');
console.log(res);
Unfortunately o am getting TS error 'Type 'T[K]' cannot be used to index type '{}'.'
Is there anything to do to fix this error?