95

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

5 回答 5

79

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} ];
于 2013-02-04T06:21:21.573 回答
24

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

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

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

于 2013-08-19T19:21:36.540 回答
12

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

interface bar {
    length: number;
}

let bars: bar[];
bars = [];
于 2018-03-12T16:05:47.587 回答
2

另一个解决方案:

interface bar {
    length: number;
}

bars = [{
  length: 1
} as bar];
于 2019-02-22T13:27:29.133 回答
2

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

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;
    [...]
}
于 2019-09-09T03:25:24.800 回答