Monday, 28 May 2018

Angular - The non-null assertion operator ( ! )

As of Typescript 2.0, you can enforce strict null checking with the --strictNullChecks flag. TypeScript then ensures that no variable is unintentionally null or undefined.
In this mode, typed variables disallow null and undefined by default. The type checker throws an error if you leave a variable unassigned or try to assign null or undefined to a variable whose type disallows null and undefined.
The type checker also throws an error if it can't determine whether a variable will be null or undefined at runtime. You may know that can't happen but the type checker doesn't know. You tell the type checker that it can't happen by applying the post-fix non-null assertion operator (!).
The Angular non-null assertion operator (!) serves the same purpose in an Angular template.
For example, after you use *ngIf to check that hero is defined, you can assert that hero properties are also defined.
<!--No hero, no text -->
<div *ngIf="hero">
  The hero's name is {{hero!.name}}
When the Angular compiler turns your template into TypeScript code, it prevents TypeScript from reporting that might be null or undefined.
Unlike the safe navigation operator, the non-null assertion operator does not guard against null or undefined. Rather it tells the TypeScript type checker to suspend strict null checks for a specific property expression.
You'll need this template operator when you turn on strict null checks. It's optional otherwise.

No comments:

Post a Comment