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


77

我在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中做到这一点?

更新

我提出了另一个解决方案,方法是使用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)
    ]);

在TypeScript中使用类似于C#的对象初始化器将非常有用。[ {length: 1} ]不是bar的实例,但如果受支持,new bar() { length = 1 }将是bar的实例。也许我们应该对此提出建议?
orad 2013年

Answers:


66

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

8
使事情更清晰和类型安全:bars:bar[]=[{length:1}]
Patrice

有没有定义类的方法吗?
blackiii

1
问题是关于如何在类中初始化数组。如果不使用类,则无法在类中初始化数组。
Ryan Cavanaugh

20

如果您确实想拥有命名参数,并且让您的对象成为类的实例,则可以执行以下操作:

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

另外,这里是打字稿问题跟踪器上的相关项目。


为问题链接+1。您还可以将初始化器值options? : {length?: number; height?: number;}
设为


1

另一个解决方案:

interface bar {
    length: number;
}

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

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;
    [...]
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.