Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

javascript - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...