0Pricing
TypeScript Academy · Lesson

Non-null Assertion Operator

Use the ! operator to assert a value is not null or undefined.

The Non-Null Assertion Operator

The postfix ! operator tells TypeScript 'this value is not null or undefined here.' It removes those from the type without any runtime check.

function firstChar(s: string | null): string {
  return s!.charAt(0); // assert s is not null
}
console.log(firstChar('hello'));

Where You Place the !

The ! goes immediately after the expression you're asserting, before any further access. It strips null | undefined from that expression's type.

type Box = { value?: number };
const box: Box = { value: 7 };
const n: number = box.value!; // value is number | undefined -> number
console.log(n);

All lessons in this course

  1. The as Keyword for Type Assertions
  2. Non-null Assertion Operator
  3. Double Assertions and Their Risks
  4. Assertions vs Type Guards
← Back to TypeScript Academy