Course contentsShow
← TypeScript
Lesson 967 of 1,79622. The never TypeFree lesson

Assertion Helper Functions

Creating reusable assert() helpers that throw on false conditions and return never.

Assertion Helper Functions

What you'll learn: How to create reusable helper functions that validate conditions and use never to tell TypeScript code is safe or unreachable.

What Are Assertion Helper Functions?

Assertion helper functions are reusable utilities that check a condition and throw an error if it's false. The key TypeScript feature: they have a return type of never, which signals to the compiler that if the function returns at all, the condition must be true.

These helpers combine runtime validation with compile-time type narrowing, letting you centralize your safety checks.

The Basic Pattern

function assert(condition: boolean, message: string): asserts condition {
  if (!condition) {
    throw new Error(message);
  }
}

// Usage
function processValue(value: unknown) {
  assert(typeof value === 'string', 'Value must be a string');
  // TypeScript now knows value is a string here
  console.log(value.toUpperCase());
}

Notice the asserts condition syntax. This tells TypeScript: "If this function returns normally, the condition is true."

Creating Typed Assertions

You can make assertions that narrow to specific types:

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

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

These helpers clean up repetitive narrowing code throughout your application.

Think of It Like a Bouncer

An assertion helper is like a bouncer at a club entrance. If someone doesn't meet the requirements, they're thrown out (error). Everyone who passes through has been verified—and everyone inside knows it.

Key Takeaway: Assertion helper functions with never return types centralize runtime validation while enabling TypeScript to narrow types after the check, combining safety and reusability in one pattern.