How does the non-null assertion operator (!) differ from actually checking and narrowing a value?
Short answer
The ! operator tells the COMPILER 'trust me, this is definitely not null/undefined here', silencing the type error WITHOUT adding any runtime check — if you're wrong, it still throws a runtime TypeError just like plain JavaScript would, whereas a real if-check or optional…
Advertisement
AModel answer
The ! operator tells the COMPILER 'trust me, this is definitely not null/undefined here', silencing the type error WITHOUT adding any runtime check — if you're wrong, it still throws a runtime TypeError just like plain JavaScript would, whereas a real if-check or optional chaining actually protects against that at runtime.
function getLength(value: string | null) {
return value!.length; // compiles, but throws at runtime if value is actually null
}
// Safer alternative:
function getLengthSafe(value: string | null) {
return value?.length ?? 0;
}Real-world example
Using ! sparingly and only when you have external knowledge the compiler can't infer, like a DOM query you know will always succeed.
Likely follow-ups
- Why is overusing the non-null assertion operator considered a common TypeScript anti-pattern?
Related topics