Sub topic 9
The non-null assertion (!) and its risks
This chapter assumes you know union types such as string | null, you have strictNullChecks turned on, and you can narrow a value with an if check. Here you will learn what the postfix ! operator does, what it does not do, when it is justified, and what to use in its place.
What the operator does
The non-null assertion operator is a ! written after an expression. It tells the compiler to treat the expression's type as if null and undefined were removed.
const scores = new Map<string, number>([["ada", 10]]);
const ada = scores.get("ada"); // number | undefined
const adaSure = scores.get("ada")!; // numberThe type of adaSure is NonNullable<number | undefined>, which is number. The operator changes only what the compiler believes. It generates no code. After compilation, the line reads const adaSure = scores.get("ada");, and the ! is gone.
You can put ! in front of a property access, an index, or a call:
declare const user: { name: string; tags?: string[]; onLeave?: () => void } | undefined;
const name = user!.name;
const firstTag = user!.tags![0];
user!.onLeave!();Each ! here is a separate promise to the compiler that the value in front of it is present.
What goes wrong at runtime
Because nothing is checked, a wrong promise surfaces later, as an ordinary JavaScript error.
const scores = new Map<string, number>([["ada", 10]]);
const ada = scores.get("ada")!;
console.log(ada + 1); // 11
const bob = scores.get("bob")!; // typed number, actually undefined
console.log(bob.toFixed(1)); // TypeError: Cannot read properties of undefinedThe compiler accepts every line. The error appears at the toFixed call, which can be far from the ! that caused it. If bob were passed through three functions first, the stack trace would point at code that looks correct.
The assertion also does not stop null from spreading. A ! on a value that is null still produces null at runtime, now carrying a type that says it cannot be.
How it compares with similar tools
The ! operator is one of several ways to get past a nullable type. They differ in whether they check anything.
| Tool | Checks at runtime | Effect on type | Failure mode |
|---|---|---|---|
| `if (x == null) return;` | Yes | Narrows to non-null | None, you handle the case |
| `x ?? fallback` | Yes | Removes null and undefined | Wrong default, but no crash |
| `x?.prop` | Yes | Adds `undefined` to the result | Absent value moves downstream |
| `assertDefined(x)` | Yes, throws | Narrows to non-null | Clear error at the right place |
| `x!` | No | Removes null and undefined | Crash later, far from the cause |
| `x as string` | No | Replaces the type | Same, and it also hides other mismatches |
x! is narrower than a cast. A cast such as x as string can replace the type with anything the compiler thinks is compatible. The ! operator only removes null and undefined, so it cannot silently convert a number | undefined into a string. It is still unchecked.
Narrowing that the compiler loses
Many uses of ! start with a narrowing that was lost, not one that was never done. Property narrowing does not survive into a callback, because the compiler cannot know the property is unchanged when the callback runs later.
interface User {
name: string;
}
interface State {
user: User | null;
}
function render(state: State): void {
if (state.user === null) {
return;
}
console.log(state.user.name); // fine here
setTimeout(() => {
// Error: 'state.user' is possibly 'null'.
console.log(state.user.name);
}, 0);
}Two fixes are common. The first is state.user!.name, which compiles but promises something the compiler cannot verify: that nobody sets state.user = null before the timer fires. The second is to copy the value into a const, which the compiler can trust:
function renderSafe(state: State): void {
const user = state.user;
if (user === null) {
return;
}
setTimeout(() => {
console.log(user.name);
}, 0);
}The const version is checked and stays correct if the code around it changes. It also costs one line, so this is rarely a hard call.
Prefer a checked alternative
If you are certain a value is present, you can turn that certainty into a check. An assertion function narrows the type and throws a clear error when the certainty is wrong.
function assertDefined<T>(
value: T,
message: string
): asserts value is NonNullable<T> {
if (value === null || value === undefined) {
throw new Error(message);
}
}
const root = document.querySelector("#app"); // Element | null
assertDefined(root, "Missing #app element");
root.classList.add("ready"); // root is Element hereThe failure now happens at the line where the assumption was made, and the message names the missing thing. The cost is a function call and a branch, which is negligible next to the debugging time it saves.
For lookups where a missing key is a real possibility, handle it instead of asserting:
const scores = new Map<string, number>([["ada", 10]]);
function scoreFor(name: string): number {
const score = scores.get(name);
if (score === undefined) {
throw new Error(`No score recorded for ${name}`);
}
return score;
}When the assertion is justified
The operator is a reasonable choice when all of these hold:
- You know the value is present because of an invariant that the type system cannot express.
- The place where the invariant is established is close to the
!, ideally in the same function. - A wrong assumption would be a programming bug, not a bad input or a missing record.
Three typical cases follow.
- Test code. A test that looks up a fixture it just created gains little from defensive branches. A thrown
TypeErrorin a test is an acceptable failure. - Immediately after a check the compiler cannot link. For example,
if (queue.length > 0) { const next = queue.shift()!; }. The method signature saysshiftcan returnundefined, and the length check does not narrow it. - Framework-managed lifecycles. A value is set by a framework before your code runs, and the framework documents that guarantee.
Even in these cases, add a short comment that states the invariant. A bare ! forces the next reader to rediscover why it is safe.
const queue: string[] = ["a", "b"];
while (queue.length > 0) {
// Safe: the loop condition guarantees at least one element.
const next = queue.shift()!;
console.log(next.toUpperCase());
}When it is not justified
Avoid ! in these situations:
- Data from outside your program. Parsed JSON, form fields, query strings, and API responses can be missing for reasons you do not control. Validate them instead.
- Silencing an error you do not understand. If the compiler reports that a value may be
nulland you do not know why it would be, find out first. The error often points to a real path. - Values that can change between check and use. Anything modified by callbacks, timers, or other modules can be reset before you read it.
- Chains that already short-circuit. In
user?.address!, the?.yieldsundefinedwheneveruseris missing, and the!hides that. The type then claims a value exists when the optional chain just said it might not.
Definite assignment: a related use of `!`
The same character appears in a different position in class declarations. A property declared as name!: string is a definite assignment assertion. It tells the compiler that the property will be assigned before it is read, even though the constructor does not assign it. It has the same trade-off: the compiler stops checking, and a wrong promise shows up as an undefined at runtime. The next chapter covers it in detail.
Keeping it under control
Most teams limit the operator with tooling rather than willpower. The @typescript-eslint/no-non-null-assertion rule reports every use, and you can set it to warn so that existing uses stay visible. The @typescript-eslint/no-non-null-asserted-optional-chain rule specifically reports the a?.b! pattern described above. With either rule on, a ! needs a deliberate override and a reviewer's attention.
A practical review habit is to ask of each !: what line proves this value is present, and what would break that proof? If the answer is not obvious from the surrounding lines, replace the ! with a check.
Exercise
The following function compiles. Explain what happens when findAge(["ada"], "bob") runs, then rewrite the function so that a missing name produces a clear error and the ! is gone.
const ages = new Map<string, number>([["ada", 36]]);
function findAge(names: string[], target: string): string {
const name = names.find((n) => n === target)!;
return name.toUpperCase();
}
Show answer
names.find returns undefined because "bob" is not in the array, but the ! makes the compiler treat the result as string. No check runs, so name.toUpperCase() throws "TypeError: Cannot read properties of undefined (reading 'toUpperCase')". The error points at toUpperCase, not at the lookup. A checked version:
function findName(names: string[], target: string): string {
const name = names.find((n) => n === target);
if (name === undefined) {
throw new Error(Name not found: ${target});
}
return name.toUpperCase();
}
The if both narrows name to string and fails with a message that names the missing value.
Exercise
A teammate writes const city = user?.address!.city; where address is optional on User. Which part is unsafe, and what would you write instead?
Show answer
If user is undefined, user?.address short-circuits and the whole chain evaluates to undefined. If user exists but has no address, the ! removes undefined from the type, and .city then throws at runtime. The ! claims address is present without any check. Write const city = user?.address?.city;, which has type string | undefined, and add ?? "unknown" if a default is acceptable.