I'm trying to declare an array of object in Typescript. However, I'm facing error retrieving the object. Below is my code. Image shows output of this.attachments.
info: Info[];
if (this.attachments.length > 0) {
this.previewInfo(this.attachments);
}
previewInfo(infos) {
this.info = [];
for (let i = 0; i < infos.length; i++) {
let reader = new FileReader();
reader.onload = (e: any) => {
var temp = new Info;
temp = {
id: i,
url: e.target.result,
message: ""
}
this.info.push(temp);
}
reader.readAsDataURL(infos[i]);
}
}
The result I get contains an empty array in front which looks like this.
[]0: {id: 0, url: "test1", message: ""}
1: {id: 1, url: "test2", message: ""}
2: {id: 2, url: "test3", message: ""}
This causes undefined when I try to retrieve them using
this.info[0]
If I skip the second line which is this.info=[], I'm getting an error which says
Cannot read property '0' of undefined
Did I declare it wrongly? How can I retrieve info by index?

this, but you are trying to accessinfowiththisin next line,this.infowill create new info object in your context which I believe is some event handler, now if you try to access this.info when you remove the second you will get an error because there is not anyinfoonthiscontext, read tylermcginnis.com/this-keyword-call-apply-bind-javascript & developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…thisin typescript.