Basics
Challenges
Classes
Debugging
Events
External Files
Flow Control
Forms
Functions
Html Elements
Installation
Interfaces
Keywords
Modules
Namespaces
Operators
Reference Files
String
Types
If you look closely at the document.getElementById
method, you will notice that the
method returns an HtmlElement or a null type. Since we like to enabled strict null checks
in our code to disallow null returns, this will cause an error.
The way to overcome this is to do two things (shown below):
non-null assertion operator
. We want to assert to the compiler
that we know more about this assignment that the compiler does. Even though our message variable type can be of
HtmlElement or null types, the innerHTML property cannot! Here, we tell the compiler to "be quiet" and we assert that
it will be non-null regardless.
Since, by nature, the innerHTML property of the document element only can be assigned a string and not a null, we want to assert that is not going to be null. The non-null assertion operator is the ! character.
Note: should you choose to use jQuery, it seems to still handle all of this better. No need for all that.