It is a way to tell the compiler
“this expression cannot be null or undefined here, so don’t complain about the possibility of it being null or undefined.”
Sometimes the type checker is unable to make that determination itself.
The bang operator tells the compiler to temporarily relax the “not null” constraint that it might otherwise demand. It says to the compiler: “As the developer, I know better than you that this variable cannot be null right now”.
“Just throw in an exclamation mark to make the code compile” is not very good advice.
The null assertion operator is not one to be used lightly as it is very easy to abuse in ways that will either hide bugs or cause them.
Optional chaining is better when you are trying to call a nested function because it will simply do nothing if something is undefined along the way.
Whereas assertion operator will result in an error being thrown.
Null assertion operators should only ever be used when you know for a fact that a variable could not possibly be null or undefined.
If there’s a chance that that is not the case, do the null check.
Example usage:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class Test { public opName?:string = "hahah"; public data?:Data; // = new Data(); } class Data { public secret: string = 'my secret code'; display() : string | undefined { return "hohoho"; } } let a = new Test(); let result = a.data!.display(); if (result) console.log(result); |
When Test’s data property is undefined, we get runtime error. When it is defined, we get “hohoho”.