[英]Element implicitly has an 'any' type because index expression is not of type 'number'.ts(7015)
[英]TypeScript TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'
我在我的 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;
}
不是 OP 的直接问题,但对于在不受其控制的库中遇到此错误的用户,可以通过添加以下内容来抑制此错误:
{
...
"suppressImplicitAnyIndexErrors": true,
...
}
到tsconfig.json
文件。
我用它来解决它,所以我可以使用 window 对象。
//in js code somewhere
window.DataManager = "My Data Manager";
//in strict typescript file
let test = (window as { [key: string]: any })["DataManager"] as string;
console.log(test); //output= My Data Manager
我实际上正在使用React ,当我通过自定义键(即myObj[myKey] =
)分配对象的属性时出现此错误。 为了解决它,我只是用作keyof :
interface IMyObj { title: string; content: string; }
const myObj: IMyObj = { title: 'Hi', content: 'Hope all is well' };
const myKey: string = 'content';
myObj[myKey as keyof IMyObj] = 'All is great now!';
这明确告诉 Typescript 您的自定义字符串 ( myKey ) 属于您用于声明对象 ( myObj ) 的接口/类型的一组属性。
PS:另一种获取属性值的方法显示在 Github 上通过extends关闭的Typescript 问题:
interface IMyObj { title: string; content: string; } const myObj: IMyObj = { title: 'Hi', content: 'Hope all is well' }; const myKey: string = 'content'; const getKeyValue = <T extends object, U extends keyof T>(obj: T) => (key: U) => obj[key]; console.log(getKeyValue(myObj)(myKey));
在 tsconfig.json 中
compilerOptions:{
"suppressImplicitAnyIndexErrors": true,
"strictNullChecks":false,
"strictPropertyInitialization": false,
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.