How to add index signature in TypeScript
The type of your accumulator in the .reduce
call is almost certainly the issue. Since it is just given as {}
, that's what its type is inferred as, and the type {}
doesn't have an index signature. You can fix this by casting your initial value so that it does include a signature:
var counts = data.reduce((newArray, item) => {
let time = item.time;
if (!newArray.hasOwnProperty(time)) {
newArray[time] = 0;
}
newArray[time]++;
return newArray;
}, {} as {[key: string]: any}); // <-- note the cast here
I gave the index signature type any
, but you may want to make it something more specific for your particular case.
The correct types for your array would be:
Array<{time: string}>
or:
{time: string}[]
or:
{[key: number]: {time: string}}