我在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
}
];
有没有办法在打字脚本中做到这一点?
UPDATE
我想出了另一个解决方案,使用一个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)
]);