Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
Unable to push elements to Interface Collection in Typescript

I have two interfaces like below:

 export interface ICard
 {
     cardNumber:string;
     cardAddress: string;
     city: string;
 }
 export interface IStudent
 {
     cards: ICard[];
     name:string;
  }

In my typescript(.ts) file, i have initialized below in my class

   private student: IStudent = <IStudent>{}; // Initializing my interface;
   private cardDetails: ICard[];        // Unable to use the same initialization like above

In my function, below i was trying to add multiple cards to my cardDetails and assigning cardDetails to my IStudent interface.

    loadStudentCards()
    {
       var card: ICard = <ICard>{}// Initializing here.
        card.cardNumber = "12345";
        card.cardAddress = "Some address";
        card.city = "Seattle";

       this.cardDetails.push(card); //  This is the place i am seeing error "Cannot read property 'push' of undefined"
         this.student.cards = this.cardDetails;
       }

This is the place i am seeing error "Cannot read property 'push' of undefined"

This might be simple question, but not sure on how to initialize the interface array object here. Can someone throw a hint here?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

That's because you haven't assigned any value to cardDetails.
It should be:

var cardDetails: ICard[] = []; 

Also, you can use the other form of type assertion (casting):

var student: IStudent = {} as IStudent;

Last thing, you can't use var (or let/const) when defining class members, it should be:

class MyClass {
    private cardDetails: ICard[] = []; 
    ...
}

Not sure if it's an actual part of your code or you just posted an example.

over 4 years ago · Santiago Trujillo Relatório

0

Use the below code which is much readable and best practice as well

loadStudentCards()
    {
       let card: ICard = {
               cardNumber : "12345",
               cardAddress : "Some address",
               city : "Seattle"
       }
       this.cardDetails= new Array<ICard>();

       this.cardDetails.push(card); 
       this.student.cards = this.cardDetails;
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda