What is the Exclamation Mark (!) or “Bang” Operator in TypeScript When Dereferencing

The exclamation mark(!) is a non-null assertion operator. It is a postfix expression that informs TypeScript that the preceding expression is not null or undefined.

By using the ! operator, you’re telling TypeScript to trust that the value is present, and it should not raise a type error. It’s a way of overriding TypeScript’s strict null checks.

However, using the non-null assertion operator comes with a risk: if the value is null or undefined, you might encounter runtime errors. Therefore, using this operator only when you are confident that the value exists or when you have checks in place to handle null or undefined values is recommended.

Remember that overusing the non-null assertion operator can lead to less safe code, as it can suppress legitimate type errors. So use it cautiously and only when you’re sure that the value cannot be null or undefined.

Leave a Comment