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.
An array is a special type of data type which can store multiple values of different data types sequentially using a special syntax. TypeScript supports arrays, similar to JavaScript.
There is no difference at all. Type[] is the shorthand syntax for an array of Type . Array<Type> is the generic syntax. They are completely equivalent.
An array of Objects is used to store a fixed-size sequential collection of elements of the same type. TypeScript Arrays are themselves a data type just like a string, Boolean, and number, we know that there are a lot of ways to declare the arrays in TypeScript.
The structure of the tuple needs to stay the same (a string followed by a number), whereas the array can have any combination of the two types specified (this can be extended to as many types as is required).
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With