Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate, initialize and populate an array in TypeScript?

I have the following classes in TypeScript:

class bar {     length: number; }  class foo {     bars: bar[] = new Array(); } 

And then I have:

var ham = new foo(); ham.bars = [     new bar() {          // <-- compiler says Expected "]" and Expected ";"         length = 1     } ]; 

Is there a way to do that in TypeScript?

UPDATE

I came up with another solution by having a set method to return itself:

class bar {     length: number;      private ht: number;     height(h: number): bar {         this.ht = h; return this;     }      constructor(len: number) {         this.length = len;     } }  class foo {     bars: bar[] = new Array();     setBars(items: bar[]) {         this.bars = items;         return this;     } } 

so you can initialize it as below:

var ham = new foo(); ham.setBars(     [         new bar(1).height(2),         new bar(3)     ]); 
like image 223
Ray Cheng Avatar asked Feb 04 '13 05:02

Ray Cheng


People also ask

How do you initialize a number array in TypeScript?

An array in TypeScript can be initialized using the empty array value and Array type, assigned to a custom type. Instead of the var products : Array<Product> = []; , one can also use the var products : Product[] = []; , and obtain the same functionality and the typing support by TypeScript.

How do you populate an array of objects in TypeScript?

To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!

How do you declare and populate an array?

To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15}; Or, you could generate a stream of values and assign it back to the array: int[] intArray = IntStream.

How do you initialize an empty array in TypeScript?

To declare an empty array for a type variable, set the array's type to Type[] , e.g. const arr: Animal[] = [] . Any elements you add to the array need to conform to the specific type, otherwise you would get an error. Copied!


1 Answers

There isn't a field initialization syntax like that for objects in JavaScript or TypeScript.

Option 1:

class bar {     // Makes a public field called 'length'     constructor(public length: number) { } }  bars = [ new bar(1) ]; 

Option 2:

interface bar {     length: number; }  bars = [ {length: 1} ]; 
like image 191
Ryan Cavanaugh Avatar answered Sep 28 '22 09:09

Ryan Cavanaugh