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.

Assertion functions & user-defined type guards is a free TypeScript Academy lesson on CoddyKit — lesson 3 of 3. 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 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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

Type guard function

A type guard returns x is T, enabling smart narrowing in branches and helpers.

type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; size: number };

type Shape = Circle | Square;

function isCircle(s: Shape): s is Circle {
  return s.kind === "circle";
}

function area(s: Shape): number {
  if (isCircle(s)) {
    return Math.PI * s.radius ** 2; // s is Circle here
  }
  return s.size * s.size; // s is Square here
}

console.log(area({ kind: "circle", radius: 2 }));

Guards in filter

Guards can be predicates for array methods (e.g., filter) to refine element types cleanly.

type Item = { id: number } | null | undefined;

function isPresent<T>(x: T | null | undefined): x is T {
  return x != null;
}

const items: Item[] = [{ id: 1 }, null, undefined, { id: 2 }];
const present = items.filter(isPresent);
// present has type { id: number }[]
console.log(present.map(i => i.id));

Assert on runtime data

Combine parsing with an assertion to fail fast when a value is not the expected type.

function parseJson(s: string): unknown {
  return JSON.parse(s);
}

try {
  const data = parseJson("{\"name\":\"Ada\"}");
  assertIsString(data); // will throw, because data is object
} catch (e) {
  console.log("Handled:", e instanceof Error ? e.message : e);
}

Guidelines

Guidelines:

  • Assertions must throw on failure.
  • Prefer guards (x is T) for branching logic.
  • Use assertions at API boundaries (I/O, JSON, DOM).

Assertion function check

Quick check: What does an assertion function with asserts x is string guarantee?

Recap

Recap: Use assertion functions to enforce types after checks and user-defined type guards to narrow branches and collections.

Frequently asked questions

Is the “Assertion functions & user-defined type guards” lesson free?

Yes — the full text of “Assertion functions & user-defined type guards” is free to read here on the web, and the TypeScript Academy course includes 3 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 “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. 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 3 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Assertion functions & user-defined type guards” 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. Function overloads & call signatures
  2. this parameter typing; void, never
  3. Assertion functions & user-defined type guards
← Back to TypeScript Academy