У меня есть следующие классы в 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)
]);
Другое решение:
interface bar {
length: number;
}
bars = [{
length: 1
} as bar];
Если требуется 'добавить' дополнительные объекты к странице, можно хотеть создать массив карт. Это - то, как я создал массив карт и затем добавил результаты к нему:
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;
[...]
}