Basics

Challenges

Classes

Cookies

Debugging

Events

External Files

Flow Control

Forms

Functions

Html Elements

Installation

Interfaces

Keywords

Modules

Namespaces

Operators

Reference Files

String

Types

TypeScript - Non-Null Assertion Operator

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):

  • use a union type to allow your variable to be nullable. Since getElementById returns a HtmlElement or a null, our variable has to have the same signature.
  • use a 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.