Vyhledávání na webu

Jak vytvořit instanci, inicializovat a naplnit pole v TypeScriptu?


Mám následující třídy v TypeScriptu:

class bar {
    length: number;
}

class foo {
    bars: bar[] = new Array();
}

A pak mám:

var ham = new foo();
ham.bars = [
    new bar() {          // <-- compiler says Expected "]" and Expected ";"
        length = 1
    }
];

Existuje způsob, jak to udělat v TypeScriptu?

AKTUALIZACE

Přišel jsem s dalším řešením tím, že jsem měl metodu set vracející sama sebe:

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 ji můžete inicializovat následujícím způsobem:

var ham = new foo();
ham.setBars(
    [
        new bar(1).height(2),
        new bar(3)
    ]);

Odpověď č. 1

V JavaScriptu nebo TypeScriptu neexistuje syntaxe inicializace polí pro objekty jako tato.

Možnost 1:

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

bars = [ new bar(1) ];

Možnost 2:

interface bar {
    length: number;
}

bars = [ {length: 1} ];

Odpověď č. 2

Pokud opravdu chcete mít pojmenované parametry a zároveň, aby vaše objekty byly instancemi vaší třídy, můžete udělat následující:

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

Tady je také související položka na trackeru problémů TypeScriptu.

Odpověď č. 3

Jednoduché řešení by mohlo být:

interface bar {
    length: number;
}

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

Související články