0Pricing
TypeScript Academy · Lesson

Non-null Assertion Operator

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

Non-null Assertion Operator is a free TypeScript Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the TypeScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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);

Asserting Non-Null After a Guard

Sometimes you've logically ensured a value is present, but the compiler can't follow the reasoning. The ! lets you proceed. Even so, an actual runtime check is usually clearer.

const list: Array<string | null> = ['a', null, 'c'];
const present = list.filter((x) => x !== null);
// TS may still see string | null; assert if certain:
console.log(present[0]!.toUpperCase());

Compile-Time Only, Again

Like as, the ! operator is erased at runtime. It performs no check. If the value really is null, you'll get a runtime error despite the compiler being satisfied.

function risky(s: string | null): number {
  return s!.length; // no runtime guard
}
console.log(risky('hi'));
// risky(null) would throw at runtime

The Danger of !

If you assert non-null on a value that can truly be null, you've created a hidden bug. The compiler stops warning you, so the error surfaces only when that null actually appears in production.

type User = { name?: string };
const u: User = {};
// const len = u.name!.length; // compiles, crashes at runtime
console.log('name is undefined here -> ! would crash');

Prefer a Real Check

Whenever practical, replace ! with an actual null check or optional chaining. The safe version costs one line and eliminates an entire class of runtime crashes.

type User = { name?: string };
function nameLen(u: User): number {
  if (u.name) return u.name.length; // checked
  return 0;
}
console.log(nameLen({ name: 'Ada' }), nameLen({}));

Definite Assignment Assertion

A related feature is the definite assignment assertion: let x!: T. It promises the compiler that x will be assigned before use, even though it isn't initialized at declaration.

let token!: string; // promise: assigned before use
function init() { token = 'abc123'; }
init();
console.log(token.length);

Definite Assignment in Classes

This is common in classes where a property is set by a framework or an init method rather than the constructor. The ! after the property name silences the 'not definitely assigned' error.

class Service {
  config!: { url: string }; // set later by setup()
  setup() { this.config = { url: '/api' }; }
}
const s = new Service();
s.setup();
console.log(s.config.url);

Use Definite Assignment Carefully

The definite assignment assertion is another promise the compiler can't verify. If you access the property before assigning it, you'll read undefined at runtime with no warning.

class Late {
  data!: number[];
  read() { return this.data.length; } // crashes if called before init
}
const l = new Late();
l.data = [1, 2];
console.log(l.read());

! vs Optional Chaining

Don't reach for ! when ?. would do. Optional chaining handles null safely at runtime, while ! merely silences the compiler. They solve different problems.

type Cfg = { db?: { host?: string } };
const c: Cfg = {};
console.log(c.db?.host ?? 'localhost'); // safe
// c.db!.host! would crash here

When ! Is Justified

The ! operator is reasonable when you have a genuine guarantee the compiler can't express — for example, a value you just pushed and immediately read. Even then, document why it's safe.

const cache = new Map<string, number>();
cache.set('hits', 0);
// We just set it, so get is non-null:
const hits = cache.get('hits')!;
console.log(hits);

Quick Check

Test your understanding of the non-null assertion operator.

Recap: Non-Null Assertion

You learned that:

  • The postfix ! removes null | undefined from a type at compile time only.
  • It performs no runtime check, so a wrong assertion still crashes.
  • let x!: T is the definite assignment assertion for later-initialized values.
  • Prefer real checks or optional chaining; reserve ! for genuine guarantees.

Next, double assertions and their risks.

const map = new Map<string, number>();
map.set('a', 1);
const v = map.get('a')!;
console.log(v);

Frequently asked questions

Is the “Non-null Assertion Operator” lesson free?

Yes — the full text of “Non-null Assertion Operator” is free to read here on the web, and the TypeScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the TypeScript Academy course, upgrade to CoddyKit PRO.

What will I learn in “Non-null Assertion Operator”?

Use the ! operator to assert a value is not null or undefined. You practise TypeScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start TypeScript Academy?

No prior experience is required. TypeScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Non-null Assertion Operator” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this TypeScript Academy lesson?

Yes. Every TypeScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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