Course contentsShow
← TypeScript
Lesson 229 of 1,7965. Type Narrowing FundamentalsFree lesson

Assertion Functions Basics

Understanding `asserts condition` and `asserts param is Type` for functions that throw on false.

Assertion Functions Basics

What You'll Learn

You'll discover how to write functions that assert conditions are true and help TypeScript narrow types by throwing errors when they aren't.

The Core Idea

Sometimes you want to validate a condition and crash your program if it's false. Unlike type predicates (which return true/false), assertion functions either succeed silently or throw an error. TypeScript has special syntax to tell the compiler: "after this function runs, this condition is guaranteed true."

There are two forms:

Form 1: asserts condition
The function asserts that some expression is truthy.

function assert(condition: unknown): asserts condition {
  if (!condition) {
    throw new Error('Assertion failed');
  }
}

let value: string | null = Math.random() > 0.5 ? "hello" : null;

assert(value !== null);
// After this line, TypeScript knows value is string (not null)
console.log(value.toUpperCase());

Form 2: asserts param is Type
The function asserts that a parameter has a specific type.

function assertIsString(value: unknown): asserts value is string {
  if (typeof value !== 'string') {
    throw new Error('Not a string!');
  }
}

let input: unknown = "test";

assertIsString(input);
// After this line, TypeScript knows input is string
console.log(input.toUpperCase());

Why This Matters

Assertion functions are like aggressive bouncers: they throw out anything that doesn't belong. Unlike type predicates that let you check and branch, assertions enforce requirements. If the assertion passes, TypeScript narrows the type for all code that follows.

Key Takeaway:
Assertion functions use asserts condition or asserts param is Type to tell TypeScript "if this function returns normally (doesn't throw), this type narrowing is now guaranteed."