我在 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)
]);