我在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;
}
或者您可以使用Map:
private applicationsByState: Map<string, any[]> = new Map<string, any[]>();
getApplicationCount(state: string) {
return this.applicationsByState.has(state) ? this.applicationsByState.get(state).length : 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句