Issue
I have a problem with the reduce method in TypeScript:
const items = {a: 10, b:20, c: 30}
const itemsTotal = Object.keys(items).reduce((accumulator: number, key: keyof typeof items ) => {
return accumulator + items[key]
}, 0)
I keep receiving the Typescript error:
Argument of type '(accumulator: number, key: "a" | "b" | "c") => number' is not assignable to parameter of type '(previousValue: string, currentValue: string, currentIndex: number, array: string[]) => string'.
Types of parameters 'accumulator' and 'previousValue' are incompatible.***
It seems that I need to define the type of the reduce method, but how?
Solution
Object.keys returns a string[], so you can't apply a reducer function that expects a keyof typeof items to it.
You could use a type assertion, since you know it's valid:
const items = {a: 10, b:20, c: 30};
const itemsTotal = Object.keys(items).reduce((accumulator, key) => {
return accumulator + items[key as keyof typeof items];
}, 0);
...but you don't need the key anyway, just use Object.values:
const items = {a: 10, b:20, c: 30};
const itemsTotal = Object.values(items).reduce((accumulator, value) => {
return accumulator + value;
}, 0);
(But frankly I'd just use a simple loop.)
Answered By - T.J. Crowder
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.