如何在TypeScript中实例化,初始化和填充数组?

Ray*_*eng 62 javascript typescript

我在TypeScript中有以下类:

class bar {
    length: number;
}

class foo {
    bars: bar[] = new Array();
}
Run Code Online (Sandbox Code Playgroud)

然后我有:

var ham = new foo();
ham.bars = [
    new bar() {          // <-- compiler says Expected "]" and Expected ";"
        length = 1
    }
];
Run Code Online (Sandbox Code Playgroud)

有没有办法在TypeScript中做到这一点?

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以你可以按如下方式初始化它:

var ham = new foo();
ham.setBars(
    [
        new bar(1).height(2),
        new bar(3)
    ]);
Run Code Online (Sandbox Code Playgroud)

Rya*_*ugh 60

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

选项1:

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

bars = [ new bar(1) ];
Run Code Online (Sandbox Code Playgroud)

选项2:

interface bar {
    length: number;
}

bars = [ {length: 1} ];
Run Code Online (Sandbox Code Playgroud)

  • 使事情更清晰和类型安全:`bars:bar [] = [{length:1}]` (8认同)
  • 问题是关于如何在类中初始化数组。没有办法在不使用类的情况下初始化类中的数组。 (2认同)

ora*_*rad 19

如果您确实想要命名参数并且您的对象是您的类的实例,则可以执行以下操作:

class bar {
    constructor (options?: {length: number; height: number;}) {
        if (options) {
            this.length = options.length;
            this.height = options.height;
        }
    }
    length: number;
    height: number;
}

class foo {
    bars: bar[] = new Array();
}

var ham = new foo();
ham.bars = [
    new bar({length: 4, height: 2}),
    new bar({length: 1, height: 3})
];
Run Code Online (Sandbox Code Playgroud)

这里还有打字稿问题跟踪器的相关项目.


Ade*_*ene 5

一个简单的解决方案可能是:

interface bar {
    length: number;
}

let bars: bar[];
bars = [];
Run Code Online (Sandbox Code Playgroud)