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?
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.
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;
}