Marko Dunovic
Marko Dunovic

Reputation: 49

how to push array to class in typeScript

so i want to push 3 instances of a class to an array in another class but i cant figure out what the problem is:

my code so far:

these are the classes

export class FudbalskiKlub implements IFudbalskiKlub {
    public registarskaOznaka: number;
    public nazivKluba: string;
    public krazakOpis: string;
    public listaIgraca: [IIgrac];

    constructor(ID: number, nazivK: string, kratakOP: string, listaIG: [IIgrac]){
        this.registarskaOznaka = ID;
        this.nazivKluba = nazivK;
        this.krazakOpis = kratakOP;
        this.listaIgraca = listaIG;
    }
}


export class Igrac implements IIgrac {
    public registarskaOznaka: number;
    public imeIgraca: string;
    public prezimeIgraca: string;
    public godisteIgraca: number;
    public prvaPostava: boolean;
    constructor(iDIgrac: number, imeIg: string, prezimeIg: string, godisteIg: number, prvaPo: boolean) {
        this.registarskaOznaka = iDIgrac;
        this.imeIgraca = imeIg;
        this.prezimeIgraca = prezimeIg;
        this.godisteIgraca = godisteIg;
        this.prvaPostava = prvaPo;
    }
}

import {Igrac} from "./index";
import {FudbalskiKlub} from "./index";

let newIgrac1 = new Igrac(13, "Nikola", "Nikolic", 1991, true);
let newIgrac2 = new Igrac(14, "Petar", "Petrovic", 1989, true );
let newIgrac3 = new Igrac(15, "Damjan", "Nikolic", 1800, false);

export let x3 = [newIgrac1, newIgrac2, newIgrac3];

export let newFudbalskiKlub = new FudbalskiKlub(1002,"My Sports Club", "Best Club In The Whole World", [newIgrac1]);

the problem is that when i try and go with x3 instead of newIgrac1 it wont let me have the 3 objects i made with the other constructor in this class and i cant figure out why.

Upvotes: 0

Views: 83

Answers (2)

basarat
basarat

Reputation: 276393

when i try and go with x3 instead of [newIgrac1] it wont let me

Fix

Change listaIG: [IIgrac] to listaIG: IIgrac[]

Why

[IIgrac] is a tuple of a single item. IIgrac[] is an array.

Upvotes: 2

mak15
mak15

Reputation: 438

As x3 is defined as an array, Try pushing to x3

x3.push(newIgrac1, newIgrac2, newIgrac3  )

Upvotes: -1

Related Questions