【发布时间】:2013-01-18 19:09:42
【问题描述】:
我在 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 中做到这一点?
更新
我想出了另一个解决方案,方法是设置一个返回自身的方法:
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)
]);
【问题讨论】:
-
在 TypeScript 中使用类似于 C# 的对象初始化器会非常有用。
[ {length: 1} ]不是 bar 的实例,但如果支持,new bar() { length = 1 }将是 bar 的实例。也许我们应该为此提出功能建议?
标签: javascript typescript