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)
]);
There isn’t a field initialization syntax like that for objects in JavaScript or TypeScript.
Option 1:
Option 2: