Reputation: 1005
I have the following code I'm trying to run:
interface Datapoint {
[key: string]: number
}
const props: Array<string> = ["a", "b", "c"]
const data: Array<Datapoint> = ...
const rolled_up: Datapoint = data.reduce(function(a: Array<Datapoint>, b: Array<Datapoint>){
props.map(function(prop: string){
a[prop] += b[prop]
})
return a
})
I want to roll up my data array into a single Datapoint, where the fields are added over the array for the given properties (props
).
When I try and compile this, I get:
error TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.
on the line
a[prop] += b[prop]
What am I doing wrong?
Upvotes: 0
Views: 180
Reputation: 97282
The types for the arguments to your reduce()
function are wrong. Should be:
const rolled_up: Datapoint = data.reduce(function(a: Datapoint, b: Datapoint){
props.map(function(prop: string){
a[prop] += b[prop]
})
return a
})
Upvotes: 1
Reputation: 1005
This issue was the types in my reduce function, they should have been:
function(a: Datapoint, b: Datapoint)
Upvotes: 0