The Bang Operator

In this lesson, you will see how the bang operator is used in TypeScript.

Bang operator role

The bang operator is the use of the exclamation point symbol !. The operator can be used after a variable and before the dot to access a member.

It is officially called the “non-null assertion operator”. A variable with the value undefined or null can benefit from using the bang operator because it tells TypeScript that you know that even if the value can theoretically be null or undefined, it’s not possible for that particular usage. In a situation where the value cannot be undefined, instead of comparing against null or undefined, you could use the bang operator to access the value.

Caveat

It is important to understand that it can open the door to runtime error and a bang operator is not something you will often see in a project. Under the hood, TypeScript removes from the type of the variable, the union with null and undefined.

Note: the code below throws an error

Get hands-on with 1200+ tech skills courses.