I am finding difficulty declaring array in typescript and accessing it.
below is the code working for me
class Book {
public BookId: number;
public Title: string;
public Author: string;
public Price: number;
public Description: string;
}
class dataservice {
getproducts() {
var bk = new Book();
bk.Author = "vamsee";
bk.BookId = 1;
var bks: Book[] = [bk,bk];
return bks.length;
}
}
var ds = new dataservice();
var button = document.createElement('button');
button.onclick = function () {
alert(ds.getproducts().toString());
}
document.body.appendChild(button);
When I change my code as below it fails when trying to assign value to array item.
var bks: Book[] = new Book[2];
bks[0].Author = "vamsee";
bks[0].BookId = 1;
return bks.length;
For me to add object in a loop I have to do it the second way.
This question is related to
arrays
class
object
typescript
A cleaner way to do this:
class Book {
public Title: string;
public Price: number;
public Description: string;
constructor(public BookId: number, public Author: string){}
}
Then
var bks: Book[] = [
new Book(1, "vamsee")
];
You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.
class Book {
public BookId: number;
public Title: string;
public Author: string;
public Price: number;
public Description: string;
}
var bks: Book[] = [];
bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"}); //This is all done in JSON.
Source: Stackoverflow.com