How to Use the Non-Null Assertion Operator in TypeScript
Not-null assertion in TypeScript is the ! operator, which allows the programmer to explicitly state that a given value is neither null nor undefined. It is used when the programmer is certain that a variable or expression will not be null or undefined, even though TypeScript cannot guarantee this based on code analysis.
Example of using the non-null assertion operator:
let myValue: string | null | undefined;
myValue = "Hello, TypeScript!";
console.log(myValue!.length); // using ! to indicate to TypeScript that myValue is not null or undefined
Example of using non-null assertion operator in Angular:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: ` <div class="app">Hello Angular!</div> `,
})
export class AppComponent implements OnInit {
name!: string; // use the ! operator, otherwise the error 'Property 'name' has no initializer and is not definitely assigned in the constructor.' will be shown
ngOnInit() {
this.name = 'Hello World!';
}
}
The not-null assertion should be used cautiously because if the value actually turns out to be null or undefined, it will cause a runtime error.