[SOLVED] Property has no initializer and is not definitely assigned in the constructor

Issue

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:

Property 'user' has no initializer and is not definitely assigned in the constructor.

user is inherited from User.ts and User.ts contains the below code:

export interface User {
firstName:string,
lastName:string,
age?:number,
address?:{
    street?: string,
    city?:string,
    state?:string
}


}

Adding ? to user is showing error in some other file:

Error screenshot before adding the ?

There is another folder named users…That is the main one…Now when I add ? here, it shows me this error.

Screenshot of error after adding question mark

Solution

This is caused by TypeScript’s Strict Class Initialization.

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#strict-class-initialization

To resolve this issue you must either declare that the type can be both Foo|undefined, or utilize the ‘!’ symbol to indicate definite assignment as per the above documentation:

Case 1:

@Component({...})
export class Component {
  @Input() myInput: string|undefined;
}

We indicate that the type may be either a string or undefined.

Case 2:

@Component({...})
export class Component {
  @Input() myInput!: string;
}

In this case we utilize the ! symbol to indicate that we are aware that myInput is not initialized in the constructor and we will handle it elsewhere.

Alternate Solution

If you do not care about strict class initialization, you can disable the feature completely in your tsconfig.json by adding a flag to your compiler options

{
 "compilerOptions": {
    "strictPropertyInitialization": false
  }
}

Note: You will have to restart the TypeScript server for the compilerOptions to be reapplied. The easiest way to achieve this is to simply restart your IDE.

Answered By – Mikkel Christensen

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *