How to instantiate, initialize and populate an array in TypeScript?
A simple solution could be:
interface bar {
length: number;
}
let bars: bar[];
bars = [];
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} ];
An other solution:
interface bar {
length: number;
}
bars = [{
length: 1
} as bar];
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.