Non-Null Assertion
What
The non-null assertion operator (!) tells the compiler that a value is guaranteed to exist and is not null or undefined.
How
You add an exclamation mark after a variable name:
function send(msg?: string) {
// We assert that msg exists
console.log(msg!.toUpperCase());
}
Why
Many libraries or DOM APIs return types that include null or undefined even when you know for a fact that the value exists in your specific context. The ! operator is a quick way to satisfy the compiler without writing a full guard clause. However, like other assertions, it is unsafe; if the value actually is null, your code will crash at runtime.
Summary
Use non-null assertions sparingly when you are 100% certain a value is defined, otherwise prefer a safe guard clause.