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

推荐答案

对于JavaScript或TypeScript中的对象,没有类似的字段初始化语法.

备选方案1:

class bar {
    // Makes a public field called 'length'
    constructor(public length: number) { }
}

bars = [ new bar(1) ];

选项2:

interface bar {
    length: number;
}

bars = [ {length: 1} ];

Typescript相关问答推荐

如何声明循环数组类型?

Typescript如何从字符串中提取多个文本

如何根据参数的值缩小函数内的签名范围?

创建一个通用上下文,允许正确推断其中的子项

`((PrevState:NULL)=>;NULL)|null`是什么意思?

如何正确地对类型脚本泛型进行限制

contextPaneTitleText类型的参数不能分配给remoteconfig类型的关键参数'""'''

基于键的值的打字动态类型;种类;

TypeScrip:基于参数的条件返回类型

当方法参数和返回类型不相互扩展时如何从类型脚本中的子类推断类型

使用TypeScrip5强制使用方法参数类型的实验方法修饰符

创建一个TypeScrip对象并基于来自输入对象的约束定义其类型

map 未显示控制台未显示任何错误@reaction-google-map/api

在抽象类构造函数中获取子类型

在打印脚本中将对象类型转换为数组

为什么`map()`返回类型不能维护与输入相同数量的值?

如何从联合类型推断函数参数?

两个子组件共享控制权

我可以使用对象属性的名称作为对象中的字符串值吗?

我可以在 Typescript 中重用函数声明吗?