The code below shows how I am attempting to sum each property of an array of T and return it as T:
export function sumProperties<T extends { [k: string]: number }>(values: T[]): T {
return values.reduce((acc, cur) => {
(Object.keys(cur) as Array<keyof T>).forEach((k) => {
acc[k] = (acc[k] || 0) + cur[k];
})
return acc;
}, {} as T);
}
The line acc[k] = (acc[k] || 0) + cur[k];
is causing issues in the code.
Currently, I have a workaround using
Object.assign(acc, { [k]: (acc[k] || 0) + cur[k] });
but I would prefer not to use it. Can anyone explain the reason for this error and suggest a TypeScript safe solution?