I declared a variable to display the today's date.
today : Date = new Date();
I retrieve the informations via the console...
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.
- Initialise property in constructor
export class HomeComponent implements OnInit {
today : Date = new Date();
day: Date;
constructor() {
day = new Date();
}
// ...
}
- Initialise property inline
export class HomeComponent implements OnInit {
today : Date = new Date();
day: Date | undefined = undefined;
// ...
}