【发布时间】:2017-03-14 11:53:41
【问题描述】:
我在 Angular 2 应用程序中遇到此编译错误:
TS7015:元素隐式具有“任意”类型,因为索引表达式不是“数字”类型。
导致它的代码是:
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;
}
这对我来说没有任何意义。我想在第一次定义属性时解决它。目前我正在写:
private applicationsByState: Array<any> = [];
但有人提到问题是尝试使用字符串类型作为数组中的索引,我应该使用映射。但我不知道该怎么做。
感谢您的帮助!
【问题讨论】:
-
如果你想定义一个字典(带有字符串键),使用类型
{[key: string]: any} -
现在我在尝试使用
this.availableStates.size获取元素数量时得到TS2339: Property 'size' does not exist on type '{ [key: string]: any; }'.。
标签: javascript angular typescript