Typescript Non-null assertion operator

Sami C.
1 min readFeb 18, 2019

--

When I was taking a look at the source code of ionic today, I found out that they actively use an exclamation mark before accessing a property, I was curious.

What is this exclamation operator?

Typescript 3.3 now supports Non-null assertion operator, which basically says that an object cannot be null. When running typescript with the — strictNullChecks flag you might get: error TS2531: Object is possibly ‘null’.

To fix this you can simply make use of the exclamation operator if you’re sure that the object is not null when accessing it’s properties.

quick example

list!.values

At first sight, some people might confuse this with the safe navigation operator from angular, this is not the case!

list?.values

The ! post-fix expression operator tells the typescript compiler that a variable is not null, if this is not the case…it will crash at runtime.

Happy coding!

--

--

Sami C.
Sami C.

Written by Sami C.

Freelance Software Engineer

Responses (1)