TypeScript TS7015:元素隐含有一个' any' type是因为索引表达式的类型不是' number'

时间:2016-11-01 10:40:56

标签: javascript angular typescript

我在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> = [];

但是有人提到问题是尝试在数组中使用字符串类型作为索引,并且我应该使用映射。但我不知道该怎么做。

向你寻求帮助!

5 个答案:

答案 0 :(得分:11)

我用它来解决它,所以我可以使用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

答案 1 :(得分:8)

如果您需要键/值数据结构,请不要使用数组。

您可以使用常规对象:

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;
}

答案 2 :(得分:1)

我实际上是在 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 )的接口/类型的属性组。 / p>

P.S .:获取属性值的另一种方法是通过扩展在封闭的Typescript's issue on Github上显示:

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));

答案 3 :(得分:1)

在 tsconfig.json 中

$(function() {alert("It's loaded!");});

答案 4 :(得分:0)

抑制此错误的另一种方法是添加:

"suppressImplicitAnyIndexErrors": true,

到tsconfig.json文件。

相关问题