I encountered an issue while working on the following code snippet:
export class UserComponent implements OnInit {
user: User;
constructor() { }
ngOnInit() {
this.user = {
firstName : "test",
lastName : "test",
age : 40,
address: {
street : "Test",
city : "test",
state: "test"
}
}
}
}
The error message I received is shown in image 1:
Property 'user' has no initializer and is not definitely assigned in the constructor.
The user
object is defined by the interface User
in User.ts with the following structure:
export interface User {
firstName: string,
lastName: string,
age?: number,
address?: {
street?: string,
city?: string,
state?: string
}
}
When attempting to resolve the first error by adding a question mark (?
) to user
, another error surfaced in a different file, as illustrated in image 2:
Error occurs in the template of component UserComponent.
src/app/components/users/users.component.html:2:44 -
error TS2532: Object is possibly 'undefined'.
2 <ul class="list-unstyled" *ngIf="loaded && users?.length > 0">
~~~~~~~~~~~~~~~~~