TypeScript Reference ยท Type Operators
TypeScript non-null assertion operator
Reference for the TypeScript non-null assertion operator x!: remove null and undefined from a type, where it is safe, what it compiles to and better alternatives.
A postfix ! after an expression is the non-null assertion operator. value! has the type of value with null and undefined removed. It is a promise to the compiler: "I know this is not null here."
Like every assertion it vanishes in the JavaScript output, so it provides no protection. If the value really is null, you will get a normal runtime error a bit later, usually "Cannot read properties of null". Use it only when something outside the type system guarantees presence.
const el = document.querySelector("#app")!; // Element, not Element | null
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
expression! object!.property array![0] fn!()
| Form | Meaning |
|---|---|
x! |
x typed as NonNullable<typeof x>. |
x!.y |
Same, then property access; unlike x?.y it does not short-circuit. |
x! on a non-nullable value |
Allowed, but useless; linters flag it. |
Edge cases:
- It only strips
nullandundefined; other union members remain. - In an assignment target,
a!.b = 1is allowed and assertsais not null. - The definite assignment form
name!: stringon a class field is a different feature; see definite assignment. - It is an error to put
!before an expression (that is the logical NOT operator).
Usage notes
- Runtime: it emits nothing.
a!.bbecomesa.b. - Typical legitimate uses: values set up by a framework,
Map.getright afterhas, array access withnoUncheckedIndexedAccesswhen the index is known valid, DOM nodes in a page you control. - Prefer narrowing with
if, early return or??and?.so the compiler verifies the check. - Prefer an assertion function that throws a clear message when a value is missing: an
assertDefined(x)helper beats a silent!. - Chains like
a!.b!.c!are a smell; fix the types instead. - ESLint:
@typescript-eslint/no-non-null-assertionforbids it in strict setups. - It is not tied to
strictNullChecks: with that option off,nullandundefinedare in every type and!does nothing.