Course contentsShow
← TypeScript
Lesson 985 of 1,79623. Type AssertionsFree lesson

Non-Null Assertions with !

The postfix `!` operator asserts a value is non-null/undefined, equivalent to `as NonNullable<typeof value>`.

Non-Null Assertions with !

What you'll learn: How to use the postfix ! operator to tell TypeScript a value is definitely not null or undefined, bypassing strict null checks.

What Is the Non-Null Assertion Operator?

The postfix ! operator (the exclamation mark placed after an expression) is TypeScript's way of letting you override the compiler's caution about potentially null or undefined values. When you write value!, you're asserting: "I know better than the type checker—this value is definitely not null or undefined right now."

Under the hood, value! is equivalent to writing value as NonNullable<typeof value>, which removes null and undefined from the value's type.

When You Need It

TypeScript's strict null checks protect you from runtime errors, but sometimes you know more than the compiler. Common scenarios:

  • After manual checks: You've validated a value exists, but TypeScript's control flow analysis didn't catch it
  • Third-party library quirks: A library's types say something might be null, but you know it won't be in your usage
  • Initialization patterns: You initialize a value in a callback or method that TypeScript can't trace

Syntax and Behavior

let username: string | null = getUserName();

// Without !: TypeScript error
// const upper = username.toUpperCase(); // Error: Object is possibly 'null'

// With !: You assert it's not null
const upper = username!.toUpperCase(); // Compiles fine

The ! operator doesn't change runtime behavior—it only affects type checking. If username actually is null at runtime, you'll still get a crash.

Critical Warnings

The non-null assertion is an escape hatch, not a solution. You're disabling type safety and taking responsibility for correctness. Use it sparingly, and only when you're certain the value cannot be null or undefined.

Key Takeaway: The postfix ! operator asserts a value is non-null/undefined without runtime checks—it's a compile-time-only override that removes null | undefined from a type, equivalent to as NonNullable<typeof value>. Use it carefully, as you're trading safety for convenience.