Skip to content
Tutorials Center
My learning

Topics

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.

TypeScript
const el = document.querySelector("#app")!; // Element, not Element | null

Try it

TypeScript Where the compiler cannot see

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.

TypeScript The assertion does not guard anything

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

TypeScript
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 null and undefined; other union members remain.
  • In an assignment target, a!.b = 1 is allowed and asserts a is not null.
  • The definite assignment form name!: string on 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!.b becomes a.b.
  • Typical legitimate uses: values set up by a framework, Map.get right after has, array access with noUncheckedIndexedAccess when 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-assertion forbids it in strict setups.
  • It is not tied to strictNullChecks: with that option off, null and undefined are in every type and ! does nothing.