我在TypeScript中具有以下类:
class bar {
length: number;
}
class foo {
bars: bar[] = new Array();
}
然后我有:
var ham = new foo();
ham.bars = [
new bar() { // <-- compiler says Expected "]" and Expected ";"
length = 1
}
];
有没有办法在TypeScript中做到这一点?
更新
我提出了另一个解决方案,方法是使用set方法返回自身:
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;
}
}
因此您可以按以下方式对其进行初始化:
var ham = new foo();
ham.setBars(
[
new bar(1).height(2),
new bar(3)
]);
[ {length: 1} ]不是bar的实例,但如果受支持,new bar() { length = 1 }将是bar的实例。也许我们应该对此提出建议?