! Non-null Assertion
Last updated: 2026-10-22
! Non-null Assertion
The non-null assertion (postfix !) tells the compiler "this value is definitely not null/undefined right now", collapsing T | null | undefined into T. It performs no runtime check — if the value is actually empty, the error surfaces later at the member access — so reserve it for cases where you have truly ruled out emptiness.
| Group | Narrowing & Assertions |
|---|---|
| Kind | Operator |
| Strict mode | Not required |
ℹ️ Info The editor transpiles TypeScript to JavaScript and runs it (no type checking); see each example's Output for type-check results.
📝 Syntax
const el = document.getElementById("root")!; // HTMLElement, not HTMLElement | null
const user = map.get("alice")!; // User, not User | undefined
console.log(user.name);
⚙️ Parameters
| ! | Postfix operator placed after an expression: removes only null and undefined from the type; emits no runtime code |
|---|
Returns:No runtime effect — the ! vanishes after transpilation; at compile time it merely removes null/undefined from the type.
▶ Example
Edit the code below and click Try it to see the transpiled result:
Output:
100
no record
(Runtime output after transpilation. aliceScore + 9 type-checks because ! narrowed the type; writing scores.get("bob")! + 1 would compile but yield NaN at runtime — ! performs no check)
💡 Notes
⚠️ Note ! is a verbal guarantee with zero runtime validation. A wrong claim does not fail immediately — it throws TypeError at some later property access, which is hard to trace. Prefer if (x) or ?? whenever they fit.
ℹ️ Info ! removes only null/undefined, nothing else: x! on string | number | null yields string | number, not string.
💡 Tip A few widely accepted uses: getElementById when the element is known to exist; Map.get right after Map.set of the same key; test fixtures. Clusters of ! in core business flow are a code smell.
🏷️ Related Narrowing & Assertions
💡 Related cases
More cases coming soon.
📚 Related tutorials
❓ FAQ
Q How does ! differ from ?. (optional chaining)?
A They point in opposite directions: ! claims "definitely non-null" (still blows up if empty), while ?. admits "possibly empty" and short-circuits to undefined. Use ?. defensively; use ! only when you are sure.
Q Is ! still needed with strictNullChecks off?
A No — with strictNullChecks off, null/undefined assign to anything and ! has nothing to do. That is one reason to always keep strictNullChecks on: without it ! becomes pure noise and emptiness bugs move entirely to runtime.
Q Why do many teams disable ! via ESLint?
A Because ! silently absorbs emptiness risk and, unlike an if check, gives no compile error when refactors invalidate the assumption. Disabling it forces guards or ?? fallbacks, which is safer long term; rare justified uses get a line-level eslint-disable.