如何在 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 中有办法做到这一点吗?

更新

通过使用 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)
]);
231635 次浏览

There isn't a field initialization syntax like that for objects in JavaScript or TypeScript.

Option 1:

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


bars = [ new bar(1) ];

Option 2:

interface bar {
length: number;
}


bars = [ {length: 1} ];

If you really want to have named parameters plus have your objects be instances of your class, you can do the following:

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

Also here's the related item on typescript issue tracker.

A simple solution could be:

interface bar {
length: number;
}


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

An other solution:

interface bar {
length: number;
}


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

If you would like to 'add' additional items to a page, you may want to create an array of maps. This is how I created an array of maps and then added results to it:

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


});

Where product.ts look like...

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