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.

Lesson 3 of 38 steps

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

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.

Free to start

Learn TypeScript with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
101
Lessons
352

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. 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. The TypeScript Academy course includes 3 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 3.

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