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) ]);
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.
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!
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.
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!
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} ];
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