Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!