Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'

Im getting this compilation error in my Angular 2 app:

TS7015: Element implicitly has an 'any' type because index expression is not of type 'number'.

The piece of code causing it is:

getApplicationCount(state:string) {     return this.applicationsByState[state] ? this.applicationsByState[state].length : 0;   } 

This however doesn't cause this error:

getApplicationCount(state:string) {     return this.applicationsByState[<any>state] ? this.applicationsByState[<any>state].length : 0;   } 

This doesn't make any sense to me. I would like to solve it when defining the attributes the first time. At the moment I'm writing:

private applicationsByState: Array<any> = []; 

But someone mentioned that the problem is trying to use a string type as index in an array and that I should use a map. But I'm not sure how to do that.

Thans for your help!

like image 219
Ole Spaarmann Avatar asked Nov 01 '16 10:11

Ole Spaarmann


People also ask

How do you fix element implicitly has an any type because index expression is not of type number?

The error "Element implicitly has 'any' type because index expression is not of type 'number'" occurs when an array is indexed with a value that is not a number. To solve the error, use an object if storing key-value pairs or use a type assertion.

Has an any type because expression of type string can't be used to index type?

The error "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type" occurs when we use a string to index an object with specific keys. To solve the error, type the string as one of the object's keys.


1 Answers

If you want a key/value data structure then don't use an array.

You can use a regular object:

private applicationsByState: { [key: string]: any[] } = {};  getApplicationCount(state: string) {     return this.applicationsByState[state] ? this.applicationsByState[state].length : 0; } 

Or you can use 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; } 
like image 66
Nitzan Tomer Avatar answered Sep 22 '22 23:09

Nitzan Tomer