Ako vytvoriť inštanciu, inicializovať a naplniť pole v TypeScripte?
Mám nasledujúce triedy v TypeScripte:
class bar {
length: number;
}
class foo {
bars: bar[] = new Array();
}
A potom mám:
var ham = new foo();
ham.bars = [
new bar() { // <-- compiler says Expected "]" and Expected ";"
length = 1
}
];
Existuje spôsob, ako to urobiť v TypeScripte?
AKTUALIZÁCIA
Prišiel som s ďalším riešením tým, že som mal nastavenú metódu, ktorá vracia sama seba:
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;
}
}
takže ho môžete inicializovať nasledovne:
var ham = new foo();
ham.setBars(
[
new bar(1).height(2),
new bar(3)
]);
Odpoveď č. 1
V JavaScripte alebo TypeScripte neexistuje syntax inicializácie polí ako táto pre objekty.
Možnosť 1:
class bar {
// Makes a public field called 'length'
constructor(public length: number) { }
}
bars = [ new bar(1) ];
Možnosť 2:
interface bar {
length: number;
}
bars = [ {length: 1} ];
Odpoveď č. 2
Ak naozaj chcete mať pomenované parametre a zároveň, aby vaše objekty boli inštanciami vašej triedy, môžete urobiť nasledovné:
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})
];
Tu je tiež súvisiaca položka na zozname problémov TypeScriptu.
Odpoveď č. 3
Jednoduchým riešením by mohlo byť:
interface bar {
length: number;
}
let bars: bar[];
bars = [];
