1

I am trying to push a date object into an array and I get this error "cannot read property 'push' of undefined".

export class CalendarComponent { 
days: Date[]

showMonths() {

 const interval = new Interval();

    interval.fromMonth  = this.selectedFromMonth.number;
    interval.fromYear = this.selectedFromYear.number;
    interval.toMonth = this.selectedToMonth.number;
    interval.toYear = this.selectedToYear.number;

    for (let i = interval.fromMonth - 1; i < 11; i++) {
      const day = new Date(interval.fromYear, i, 1);
       this.days.push(day);
      // console.log(day);
      // days.push(day);
    }

    // console.log(day);
}

Why do I get this error if 'days' it is already an array and 'day' it is not undefined ?

1
  • You've given it a type but not a value. Commented Jul 21, 2018 at 8:39

2 Answers 2

8

You need to initialize your property. You have just set the type of it, but actually it is undefined.

days: Date[] = [];
Sign up to request clarification or add additional context in comments.

Comments

1

static typing is typescript future and when you compile your code to javascript typing will gone this just a help to developer during the build time.

days: Date[] is the same you sa days and the initial value is undefined

var days;

console.log(days); // => undefined

that why you need assaign days to [] empty array before you use it

days: Date[] = [];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.