0Pricing
TypeScript Academy · Lesson

Assertion functions & user-defined type guards

Write assertion functions (asserts x is T) and user-defined type guards (x is T) to narrow unknown/union values safely.

Intro

Goal: Turn runtime checks into type refinements with assertion functions and user-defined type guards for safe APIs.

Assertion function

An assertion function narrows types for subsequent code if it returns; otherwise, it must throw.

function assertIsString(x: unknown): asserts x is string {
  if (typeof x !== "string") {
    throw new Error("Expected string");
  }
}

let v: unknown = Math.random() > 0.5 ? "ok" : 42;
assertIsString(v); // after this, v is string
console.log(v.toUpperCase());

All lessons in this course

  1. Function overloads & call signatures
  2. this parameter typing; void, never
  3. Assertion functions & user-defined type guards
← Back to TypeScript Academy