Recently, I've been attempting to update a library that utilizes this function to the newest version of Typescript:
/**
* This function takes an array of entities and maps their property values into arrays
* keyed by the name of the property in each entity.
* @param entities The array of entities
* @return A single object with all the property values on the entities mapped into arrays.
*
* @example
students: Student[] = [
{id: 1, name: 'John', age: 21},
{id: 2, name: 'Jane', age: 25},
{id: 3, name: 'Alex', age: 30},
]
console.log(toArrayByObjectKey(students))
*
* Implementation credit goes to Georg as per this SO answer:
* https://stackoverflow.com/questions/55404204/attempting-to-understand-reduce-functions-for-object-mapping
*/
export function toArrayByObjectKey<E>(entities:E[]) {
let res:any = {};
for (let obj of entities)
for (let [k, v] of Object.entries(obj))
res[k] = (res[k] || []).concat(v)
return res;
};
This function used to compile without errors, but now it's giving me this message:
No overload matches this call.
Overload 1 of 2, '(o: { [s: string]: unknown; } | ArrayLike<unknown>): [string, unknown][]', gave the following error.
Argument of type 'E' is not assignable to parameter of type '{ [s: string]: unknown; } | ArrayLike<unknown; }'.
Type 'E' is not assignable to type 'ArrayLike<unknown>'.
After trying both suggestions mentioned above, running the tests results in a different type of error like this:
Error: projects/fs-collections/src/lib/src/index.spec.ts:154:41 - error TS2344: Type 'Student' does not satisfy the constraint '{ [s: string]: unknown; } | ArrayLike<unknown; }'.
Type 'Student' is not assignable to type '{ [s: string]: unknown; }'.
Index signature for type 'string' is missing in type 'Student'.
154 let s: Students = toArrayByObjectKey<Student>(students);
Any thoughts on how to resolve this issue?