We may get the message Property has no initializer and is not definitely assigned in the constructor
when adding some configuration in the tsconfig.json
file so as to have an Angular project compiled in strict mode:
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"noImplicitThis": true,
"alwaysStrict": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
Indeed the compiler then complains that a member variable is not defined before being used.
For an example of a member variable that is not defined at compile time, a member variable having an @Input
directive:
@Input() userId: string;
We could silence the compiler by stating the variable may be optional:
@Input() userId?: string;
But then, we would have to deal with the case of the variable not being defined, and clutter the source code with some such statements:
if (this.userId) {
} else {
}
Instead, knowing the value of this member variable would be defined in time, that is, it would be defined before being used, we can tell the compiler not to worry about it not being defined.
The way to tell this to the compiler is to add the ! definite assignment assertion
operator, as in:
@Input() userId!: string;
Now, the compiler understands that this variable, although not defined at compile time, shall be defined at run-time, and in time, before it is being used.
It is now up to the application to ensure this variable is defined before being used.
As an an added protection, we can assert the variable is being defined, before we use it.
We can assert the variable is defined, that is, the required input binding was actually provided by the calling context:
private assertInputsProvided(): void {
if (!this.userId) {
throw (new Error("The required input [userId] was not provided"));
}
}
public ngOnInit(): void {
// Ensure the input bindings are actually provided at run-time
this.assertInputsProvided();
}
Knowing the variable was defined, the variable can now be used:
ngOnChanges() {
this.userService.get(this.userId)
.subscribe(user => {
this.update(user.confirmedEmail);
});
}
Note that the ngOnInit
method is called after the input bindings attempt, this, even if no actual input was provided to the bindings.
Whereas the ngOnChanges
method is called after the input bindings attempt, and only if there was actual input provided to the bindings.