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:
There is another folder named users...That is the main one...Now when I add ? here, it shows me this error.
The error "Property has no initializer and is not definitely assigned in the constructor" occurs when we declare a class property without initializing it. To solve the error, provide an initial value for the class property, e.g. name: string = 'James'; or use a non-null assertion.
You can set the strictPropertyInitialization setting to false in your tsconfig. json 's compilerOptions , or --strictPropertyInitialization false on the command line to turn off this checking.
Getting ElementRef in Component ClassCreate a template reference variable for the element in the component/directive. Use the template variable to inject the element into component class using the ViewChild or ViewChildren.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With