TypeScript TS7015:元素隐式地具有"any"类型,因为索引表达式不是"number"类型 [英] TypeScript TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'

查看:732
本文介绍了TypeScript TS7015:元素隐式地具有"any"类型,因为索引表达式不是"number"类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular 2应用中遇到此编译错误:

Im getting this compilation error in my Angular 2 app:

TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.

导致它的代码段是:

getApplicationCount(state:string) {
    return this.applicationsByState[state] ? this.applicationsByState[state].length : 0;
  }

但这不会导致此错误:

getApplicationCount(state:string) {
    return this.applicationsByState[<any>state] ? this.applicationsByState[<any>state].length : 0;
  }

这对我来说没有任何意义.我想在第一次定义属性时解决它.目前,我正在写:

This doesn't make any sense to me. I would like to solve it when defining the attributes the first time. At the moment I'm writing:

private applicationsByState: Array<any> = [];

但是有人提到问题是试图将字符串类型用作数组中的索引,因此我应该使用映射.但是我不确定该怎么做.

But someone mentioned that the problem is trying to use a string type as index in an array and that I should use a map. But I'm not sure how to do that.

感谢您的帮助!

推荐答案

如果您想要键/值数据结构,则不要使用数组.

If you want a key/value data structure then don't use an array.

您可以使用常规对象:

private applicationsByState: { [key: string]: any[] } = {};

getApplicationCount(state: string) {
    return this.applicationsByState[state] ? this.applicationsByState[state].length : 0;
}

或者您可以使用地图 :

private applicationsByState: Map<string, any[]> = new Map<string, any[]>();

getApplicationCount(state: string) {
    return this.applicationsByState.has(state) ? this.applicationsByState.get(state).length : 0;
}

这篇关于TypeScript TS7015:元素隐式地具有"any"类型,因为索引表达式不是"number"类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆