如何在TypeScript中添加索引签名

Bet*_*any 4 javascript arrays typescript index-signature

我正在尝试使用reduce与Typescript来达到传入消息的总数.我对如何添加索引签名很困惑.我一直收到错误:"元素隐式有'任何'类型,因为类型'{}'没有索引签名." on变量newArray和count [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' }
    ];
Run Code Online (Sandbox Code Playgroud)

这就是我需要在rechart图中使用我的数组的方法:

        var dataWithCounts = [
        { time: '9:54', messages: 3 }, 
        { time: '9:55', messages: 4 }, 
        { time: '9:56', messages: 4 }, 
        { time: '9:57', messages: 5 }
    ];
Run Code Online (Sandbox Code Playgroud)

在这个Stack Overflow问题的"Just a Student's"答案的帮助下:对数组中的值进行分组和计数 ,我有以下内容.

        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);
Run Code Online (Sandbox Code Playgroud)

我在哪里以及如何申报索引签名?以下是我尝试过的各种事情.

  • let newArray: { [time: string] }; 并收到重复的标识符错误.

  • 在参数中添加字符串会var counts = data.reduce((newA:string, item)给出错误"元素隐式具有'任意'类型,因为索引表达式不是'number'类型."

  • 添加newA[time].toString()给我错误,"赋值表达式的左侧必须是变量或属性访问."

CRi*_*ice 9

.reduce呼叫中累加器的类型几乎肯定是个问题.因为它只是作为{},它的类型被推断为,并且类型{}没有索引签名.您可以通过转换初始值来解决此问题,以便它包含签名:

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
Run Code Online (Sandbox Code Playgroud)

我给出了索引签名类型any,但您可能希望使其更适合您的特定情况.


Jon*_*lms 5

数组的正确类型是:

Array<{time: string}>
Run Code Online (Sandbox Code Playgroud)

或者:

{time: string}[]
Run Code Online (Sandbox Code Playgroud)

或者:

{[key: number]: {time: string}}
Run Code Online (Sandbox Code Playgroud)