Home > Software engineering >  Type 'number' is not assignable to type 'Date' in Angular
Type 'number' is not assignable to type 'Date' in Angular

Time:09-03

I declared a variable to display the today's date.

today : Date = new Date();

I retrieve the informations via the console...

enter image description here

Now, I would like to create a variable to retrieve the day from the today's date.

I created the variable -> day.

today : Date = new Date();
day: Date;

I have an error message ->

error TS2564: Property 'day' has no initializer and is not definitely assigned in the 
constructor. 

I don't understand the problem?

Here is my code, thank for your help.

export class HomeComponent implements OnInit {

  today : Date = new Date();
  day: Date;


  constructor() { }

  ngOnInit(): void {

    this.day = this.today.getDate();

    console.log("Today => "   this.today);
    console.log("Day => "   this.day);        
  }

}

CodePudding user response:

You've got two options to address this error:

error TS2564: Property 'day' has no initializer and is not definitely assigned in the 
constructor. 
  1. Initialise property in constructor
export class HomeComponent implements OnInit {

  today : Date = new Date();
  day: Date;


  constructor() {
      day = new Date();
  }
// ...
}
  1. Initialise property inline
export class HomeComponent implements OnInit {

  today : Date = new Date();
  day: Date | undefined = undefined;
// ...
}
  • Related