I have this utility function that given an array and the key by which it each item should be indexed, should convert it to an object:
export const convertArrayToObject = (array: any[], key: string): any => {
const initialValue = {};
return array.reduce((obj, item) => ({
...obj,
[item[key]]: item,
}), initialValue);
};
Here's what you should expect from this utility:
>>> console.log(convertArrayToObject(
[
{
id: 'foo',
color: 'blue'
},
{
id: 'bar',
color: 'red'
}
], 'id'
));
This should log:
{
foo: {
id: 'foo',
color: 'blue'
},
bar: {
id: 'bar',
color: 'red'
}
}
The problem is, I'm using any twice and that breaks type safety for no good reason. I'm trying to write this utility function using generics but really finding it hard. Can someone help me replace the two anys with generics?