Careeroza
Non-null Assertion
The ! Operator
Putting ! after an expression removes null and undefined from its type. Use it only when you are certain the value exists.
Example
const prices = new Map<string, number>([["SKU-1", 499], ["SKU-2", 89]]);
// Map.get returns number | undefined
const a = prices.get("SKU-1")!; // we just inserted it, so it exists
console.log(a + 1);
const b = prices.get("SKU-2");
if (b !== undefined) console.log(b + 1); // safer: check instead of !Output
500 90
When ! Lies
Example
The compiler trusts the !, so this compiles but crashes at runtime with a TypeError.
const prices = new Map<string, number>([["SKU-1", 499]]);
const missing = prices.get("SKU-404")!;
console.log(missing.toFixed(2));Output
Uncaught TypeError: Cannot read properties of undefined (reading 'toFixed')