Home > Software engineering >  Why does setting a static value in array of any[] picks the record but not if set dynamically?
Why does setting a static value in array of any[] picks the record but not if set dynamically?

Time:06-20

I am trying to put the index in the array but it fails. When I put a static number

let Id: any= this.selectedID;
this.Name= this.secs[Id].Name;

but on the this.secs[Id].Name; it fails. Even it has the value i.e. 114. But when I put the same 114 statically like this:

let Id: any= this.selectedID;
this.Name= this.secs[114].Name;

then it works otherwise undefined.

this.secs is of type any and is filled on ngOnInit

Why ? I have been struggling with it for th past many hours but still not working.

CodePudding user response:

Id is declared like this let Id: any, which means that it's of any type.

Arrays in TS can only be indexed with number or string (or a subset of them), but not anything else.

When you use 114 that's accepted by TS, but when using id that doesn't work.

You can try to cast Id to number and that will work.

  • Related