我正在尝试使用 reduce 和 Typescript 来达到传入消息的总数。我对如何添加索引签名感到困惑。我不断收到错误消息:“元素隐式具有 'any' 类型,因为类型 '{}' 没有索引签名。” 在变量 newArray 和 counts[k] 上。我已经阅读了几个类似的问题,但还没有弄清楚如何将它们应用于我的特定场景。我是 JavaScript 和 TypeScript 的新手。
这是我的数组:
var data = [
{ time: '9:54' },
{ time: '9:54' },
{ time: '9:54' },
{ time: '9:55' },
{ time: '9:55' },
{ time: '9:55' },
{ time: '9:55' },
{ time: '9:56' },
{ time: '9:56' },
{ time: '9:56' },
{ time: '9:56' },
{ time: '9:57' },
{ time: '9:57' },
{ time: '9:57' },
{ time: '9:57' },
{ time: '9:57' }
];
这就是我需要我的数组在图表图中使用的方式:
var dataWithCounts = [
{ time: '9:54', messages: 3 },
{ time: '9:55', messages: 4 },
{ time: '9:56', messages: 4 },
{ time: '9:57', messages: 5 }
];
在这个 Stack Overflow 问题的“只是一个学生”的回答的帮助下:Group and count values in an array ,我有以下内容。
var counts = data.reduce((newArray, item) => {
let time = item.time;
if (!newArray.hasOwnProperty(time)) {
newArray[time] = 0;
}
newArray[time]++;
return newArray;
}, {});
console.log(counts);
var countsExtended = Object.keys(counts).map(k => {
return { time: k, messages: counts[k] };
});
console.log(countsExtended);
我在哪里以及如何声明索引签名?以下是我尝试过的各种方法。
let newArray: { [time: string] };
并收到重复标识符错误。将字符串添加到参数
var counts = data.reduce((newA:string, item)
会给我一个错误“元素隐式具有'任何'类型,因为索引表达式不是'数字'类型。”添加
newA[time].toString()
给我错误,“赋值表达式的左侧必须是变量或属性访问。”