我在 Angular 2 应用程序中遇到此编译错误:
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;
}
这对我来说没有任何意义。我想在第一次定义属性时解决它。目前我正在写:
private applicationsByState: Array<any> = [];
但是有人提到问题是尝试使用字符串类型作为数组中的索引,我应该使用映射。但我不确定该怎么做。
感谢您的帮助!
最佳答案
如果您需要键/值数据结构,则不要使用数组。
您可以使用常规对象:
private applicationsByState: { [key: string]: any[] } = {};
getApplicationCount(state: string) {
return this.applicationsByState[state] ? this.applicationsByState[state].length : 0;
}
或者您可以使用 a Map :
private applicationsByState: Map<string, any[]> = new Map<string, any[]>();
getApplicationCount(state: string) {
return this.applicationsByState.has(state) ? this.applicationsByState.get(state).length : 0;
}
关于javascript - typescript TS7015 : Element implicitly has an 'any' type because index expression is not of type 'number' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40358434/