I'm writing out some Angular samples for this blog and came across this error:

error TS2564: Property 'myButton' has no initializer and is not definitely assigned in the constructor.

when trying to create an Angular ViewChild. Here is a screenshot from within IntelliJ:

Sometimes you can solve this by following the instructions. Give the variable a default value like this:

view plain print about
1myString = '';

Or initialize it in a constructor

view plain print about
1myString: string;
2 constructor() {
3 this.myString = '';
4 }

However, an Angular ViewChild's value is set by the Angular framework as part of the component rendering code. This isn't something we really want to default.

To get rid of the error, we must declare this field as optional. Using the myString sample, it'd be like this:

view plain print about
1myString!: string;

Or with a more formal viewChild:

view plain print about
1@ViewChild('myButton')
2 myButton!: ElementRef;

Now the code can compile and run w/ errors.