I am developing a function called keyBy
that has a simple purpose.
The objective of this function is to transform an array of objects
into an object
, using a provided 'key string':
const arr = [{ name: 'Jason', age: 18 }, { name: 'Amy', age: 25 }];
console.log(keyBy(arr, 'name'));
// => { 'Jason': { name: 'Jason', age: 18 }, 'Amy': { name: 'Amy', age: 25 } }
Here is a basic implementation of the javascript function without typescript:
function keyBy(arr, key) {
let result = {};
arr.forEach(obj => {
result[obj[key]] = obj;
});
return result;
}
Currently, I have a version of my `keyBy` function in typescript that is not compiling as expected:
function keyBy<T, K extends keyof T>(arr: T[], key: K): { [key: T[K]]: T } {
// The error message states: An index signature parameter type must be 'string' or 'number'.
let result: { [key: T[K]]: T } = {};
arr.forEach(item => {
result[item[key]] = item;
});
return result;
}
You can find a screenshot of the issue in my VSCode here:
https://i.sstatic.net/T62gB.png
How can I correctly type the `keyBy` function in typescript?