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

Simple Assertion Function Syntax

Writing assertion functions with `asserts condition` to validate assumptions and narrow types.

Simple Assertion Function Syntax

You'll learn: How to write assertion functions using asserts condition syntax to validate assumptions and automatically narrow types.

What Are Assertion Functions?

Assertion functions are a special kind of function that guarantees a condition is true—or throws an error. Unlike type predicates that return boolean and let you decide what to do, assertion functions enforce the truth right there. If the assertion passes, TypeScript narrows types accordingly. If it fails, execution stops.

Think of it like a security checkpoint: either you pass through (and TypeScript knows you're safe), or you're stopped entirely.

The asserts condition Syntax

The simplest form uses the asserts keyword followed by a condition:

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

let input: unknown = 42;

assertIsNumber(input);
// After this line, TypeScript knows input is number
console.log(input.toFixed(2)); // ✓ Safe!

How It Works

The return type asserts value is number tells TypeScript: "If this function returns normally (doesn't throw), then value is definitely a number." TypeScript trusts you to implement the check correctly.

function assertIsDefined<T>(value: T | undefined): asserts value is T {
  if (value === undefined) {
    throw new Error('Value was undefined');
  }
}

let data: string | undefined = "hello";
assertIsDefined(data);
data.toUpperCase(); // ✓ TypeScript knows data is string

Key Takeaway: Assertion functions use asserts condition syntax to enforce runtime checks and automatically narrow types when the assertion succeeds, eliminating the need for manual narrowing afterward.