I am getting an error when I give
export class UserComponent implements OnInit {
user: User;
constructor() { }
ngOnInit() {
this.user = {
firstName : "test",
lastName : "test",
age : 40,
address: {
street : "Test",
city : "test",
state: "test"
}
}
}
}
I am getting this error (see image 1):
Property 'user' has no initializer and is not definitely assigned in the constructor.
user
is instantiated from User
which is declared in User.ts by this code:
export interface User {
firstName: string,
lastName: string,
age?: number,
address?: {
street?: string,
city?: string,
state?: string
}
}
If I add a question mark (?
) to user
, another error appears in some other file (see 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">
~~~~~~~~~~~~~~~~~
ngOnInit
toconstructor
when turning on strict mode, but all the tests still passed. And it's unclear what you expected in the last two screenshots - 1. making it optional in one place doesn't make it optional everywhere; and 2. if it's optionalusers?.length
is potentially undefined.users?.length
undefined? I don't want to mention the course name here..It might be against the rules of stack overflow