Ole*_*ann 25 javascript typescript angular
我在Angular 2应用程序中收到此编译错误:
TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.
Run Code Online (Sandbox Code Playgroud)
导致它的代码是:
getApplicationCount(state:string) {
return this.applicationsByState[state] ? this.applicationsByState[state].length : 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,这不会导致此错误:
getApplicationCount(state:string) {
return this.applicationsByState[<any>state] ? this.applicationsByState[<any>state].length : 0;
}
Run Code Online (Sandbox Code Playgroud)
这对我没有任何意义.我想在第一次定义属性时解决它.目前我正在写:
private applicationsByState: Array<any> = [];
Run Code Online (Sandbox Code Playgroud)
但有人提到问题是试图在数组中使用字符串类型作为索引,我应该使用映射.但我不知道该怎么做.
有你的帮助!
Nit*_*mer 25
如果需要键/值数据结构,请不要使用数组.
您可以使用常规对象:
private applicationsByState: { [key: string]: any[] } = {};
getApplicationCount(state: string) {
return this.applicationsByState[state] ? this.applicationsByState[state].length : 0;
}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用地图:
private applicationsByState: Map<string, any[]> = new Map<string, any[]>();
getApplicationCount(state: string) {
return this.applicationsByState.has(state) ? this.applicationsByState.get(state).length : 0;
}
Run Code Online (Sandbox Code Playgroud)
Rob*_*ita 13
不是OP的直接问题,而是对于不在其控制范围内的库遇到此错误的用户,可以通过添加以下命令来抑制此错误:
"suppressImplicitAnyIndexErrors": true,
到tsconfig.json文件。
CPH*_*hon 12
我实际上正在使用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!';
Run Code Online (Sandbox Code Playgroud)
这明确告诉 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));
Run Code Online (Sandbox Code Playgroud)
在 tsconfig.json 中
compilerOptions:{
"suppressImplicitAnyIndexErrors": true,
"strictNullChecks":false,
"strictPropertyInitialization": false,
}
Run Code Online (Sandbox Code Playgroud)
小智 7
我用它来解决它,所以我可以使用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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
27100 次 |
最近记录: |