VKR VKR - 1 month ago 12
TypeScript Question

Arrays in type script

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.

Answer

This is a very c# type of code:

var bks: Book[] = new Book[2];

In Javascript / Typescript you don't allocate memory up front like that, and that means something completely different. This is how you would do what you want to do:

var bks: Book[] = [];
bks.push(new Book());
bks[0].Author = "vamsee";
bks[0].BookId = 1;
return bks.length;

Now to explain what new Book[2]; would mean. This would actually mean that call the new operator on the value of Book[2]. e.g.:

Book[2] = function (){alert("hey");}
var foo = new Book[2]

and you should see hey. Try it