Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type 'number' is not assignable to type 'Date' in Angular

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);        
  }

}

>Solution :

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;
// ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading