Non-null Assertion
The non-null assertion is a postfix ! that removes null and undefined from a value's type. It is a promise to the compiler, checked by nobody, and it disappears when the code is compiled.
Detailed Explanation
Under strictNullChecks, a lot of useful values arrive as "maybe nothing". document.querySelector returns Element | null. Map.prototype.get returns V | undefined. An array's .find returns T | undefined. The compiler makes you deal with that possibility before you use the value, which is the point of the flag.
The ! operator opts out for one expression:
const root = document.querySelector("#app")!; // type is Element, not Element | null
It is a type-level operation only. tsc emits document.querySelector("#app") and nothing else — no check, no throw. If the selector misses, root is null at runtime and the failure surfaces on the next line as "Cannot read properties of null". The ! bought you a shorter line and moved the error somewhere less informative.
Compare it with two things it is often confused with:
| Syntax | When it acts | What it does |
|---|---|---|
user!.name | compile time | asserts user is not null, then reads .name; throws if wrong |
user?.name | runtime | checks user, returns undefined instead of throwing |
user ?? fallback | runtime | supplies a value when user is null or undefined |
Only the first is a type assertion. The other two are real JavaScript operators that survive compilation.
There is a related but distinct !: the definite assignment assertion on a declaration, written let socket!: WebSocket or private db!: Database on a class field. That one tells the compiler "this gets assigned before anything reads it", which silences strictPropertyInitialization for fields set in a lifecycle hook or a DI container. Same character, different position, different meaning.
When is ! acceptable? When the invariant is genuinely outside the type system and cheap to reason about locally: an element you rendered yourself two lines above, a regex capture group that the pattern guarantees, a Map.get immediately after a Map.has on the same key in the same statement. Even then, an explicit alternative is usually short:
const root = document.querySelector("#app");
if (!root) throw new Error("#app is missing from the page");
// root is Element from here on, and the failure message names the cause
That version costs one extra line and gives you a real error at the real moment. It also survives refactoring, which ! does not.
The deeper cost is that ! is invisible to review and undetectable in aggregate. A codebase with hundreds of them has effectively turned strictNullChecks off in hundreds of places, while still reporting the flag as enabled. Most teams end up enabling the @typescript-eslint/no-non-null-assertion lint rule and allowing exceptions deliberately.
Code Examples
1. What ! removes, and what it does not do.
// 1. What ! removes, and what it does not do.
const input = document.querySelector("#email"); // Element | null
input.id;
// Error: 'input' is possibly 'null'.
const forced = document.querySelector("#email")!; // Element
forced.id; // compiles
// Emitted JavaScript is identical either way:
// const forced = document.querySelector("#email");
// If the element is absent, this throws at runtime, not at the assertion.2. Map lookups: the common temptation, and the version that holds up.
// 2. Map lookups: the common temptation, and the version that holds up.
const flags = new Map<string, boolean>([["new-checkout", true]]);
const risky = flags.get("new-chekout")!; // typo; type says boolean, value is undefined
console.log(risky ? "on" : "off"); // prints "off" — a bug that never errors
function readFlag(name: string): boolean {
const value = flags.get(name);
if (value === undefined) throw new Error(`Unknown feature flag: ${name}`);
return value; // narrowed to boolean by a check that runs
}3. The other '!': definite assignment on a declaration.
// 3. The other '!': definite assignment on a declaration.
class SessionStore {
private db!: Database; // "assigned later, before any read" — silences strictPropertyInitialization
async init() {
this.db = await connect();
}
}
declare class Database {}
declare function connect(): Promise<Database>;Common Gotchas
`!` is a claim, not a check
the compiler stops warning and the runtime behaviour is unchanged. If the value really is null, you get a `TypeError` on a later line with no mention of the assertion that allowed it.
Asserting non-null does not stop the value from becoming null again
`obj.field!` narrows that one expression. After an `await`, a callback, or another function call, the compiler forgets and you assert again — which is a sign the value should have been checked once and stored in a `const`.
`!` does nothing when `strictNullChecks` is off
without the flag, `null` and `undefined` are already assignable everywhere, so the operator is a no-op. It is only meaningful in a strict project.
Do not confuse `a!.b` with `a?.b`
they look similar and behave oppositely. `!` removes the check; `?.` adds one. Typing `!` when you meant `?.` converts a safe read into a crash.