Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

angular - Property has no initializer and is not definitely assigned in the constructor

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...