Issue
Need to create a method a method that takes array of objects and keys then sums up by the passed keys, attempts so far have been unsuccessful( this is pseudo code):
const calculateTotals = <T extends object, K extends keyof T>(items: T[], ...keys : K[]) => {
let result;
if (keys.length)
{
//if I needed to sum up ALL the properties this would suffice, how to plug-in passed keys here?
result = items.reduce((r, item) => (Object.entries(item).forEach(([key, value]) => r[key] = (r[key] || 0) + value), r), {});
}
return result;
}
Is it possible to achieve this?
Solution
There's a few changes you can make to implement your function:
- Use
keys.forEach
instead ofObject.entries
- Don't use
reduce
and modify the accumulator.forEach
works best here. - Change the type to have either
T
orK
generic, but not both. Typescript struggles to maintain the relationship between two type variables.
const calculateTotals = <K extends PropertyKey>(items: Record<K, number>[], ...keys: K[]) => {
let totals: Partial<Record<K, number>> = {};
items.forEach((r) =>
keys.forEach((key) =>
totals[key] = (totals[key] ?? 0) + r[key]))
return totals;
}
Answered By - Etienne Laurin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.