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

时间:2013-02-04 05:13:39

标签: javascript typescript

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

5 个答案:

答案 0 :(得分:56)

没有像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} ];

答案 1 :(得分:18)

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

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})
];

另外here是打字稿问题跟踪器的相关项目。

答案 2 :(得分:4)

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

interface bar {
    length: number;
}

let bars: bar[];
bars = [];

答案 3 :(得分:0)

另一种解决方案:

interface bar {
    length: number;
}

bars = [{
  length: 1
} as bar];

答案 4 :(得分:0)

如果您想在页面上“添加”其他项目,则可能需要创建一组地图。这是我创建地图数组,然后向其中添加结果的方式:

import { Product } from '../models/product';

products: Array<Product>;          // Initialize the array.

[...]

let i = 0;
this.service.products( i , (result) => {

    if ( i == 0 ) {
        // Create the first element of the array.
        this.products = Array(result);
    } else { 
        // Add to the array of maps.
        this.products.push(result);
    }

});

product.ts 的位置...

export class Product {
    id: number;
    [...]
}