Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading