Skip to the content

Lesson 108 of 296

Type guards, assertion functions and exhaustive checks

What you will learn

  • Writing your own type guard functions
  • Assertion functions
  • Exhaustive checking with never
On this page

User-defined type guards

Sometimes narrowing logic is too complex to repeat. A type guard function returns a boolean, and its return type value is Type tells TypeScript what a true result means:

type Cat = { kind: "cat"; meow(): void };
type Dog = { kind: "dog"; bark(): void };

function isCat(pet: Cat | Dog): pet is Cat {
  return pet.kind === "cat";
}

function speak(pet: Cat | Dog) {
  if (isCat(pet)) {
    pet.meow();       pet: Cat
  } else {
    pet.bark();       pet: Dog
  }
}

Checking unknown data:

type User = { id: number; name: string };

function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&
    value !== null &&
    "id" in value &&
    typeof value.id === "number" &&
    "name" in value &&
    typeof value.name === "string"
  );
}

const data: unknown = JSON.parse(text);
if (isUser(data)) {
  console.log(data.name);
}

For real projects, a validation library such as Zod writes these checks for you (Lesson 114).

Filtering arrays:

const values = ["a", null, "b", undefined];
const strings = values.filter((v): v is string => v != null);      string[]

Recent TypeScript versions can infer simple type guards like this automatically, but writing the predicate is always clear.

Warning: TypeScript trusts your guard. If the function body is wrong, the types will be wrong too.

Assertion functions

Instead of returning a boolean, an assertion function throws if the check fails. Its return type asserts value is Type (or asserts condition) narrows the type for the rest of the code after it is called:

function assertIsDefined<T>(value: T, message: string): asserts value is NonNullable<T> {
  if (value === null || value === undefined) {
    throw new Error(message);
  }
}

const input = document.querySelector("input");
assertIsDefined(input, "Input missing");
input.value;          input: HTMLInputElement from here on
function assert(condition: unknown, message: string): asserts condition {
  if (!condition) throw new Error(message);
}

assert(user.role === "admin", "Admins only");

Exhaustive checks with never

When you handle a discriminated union, you want TypeScript to tell you if a new case is added and you forget to handle it.

function assertNever(value: never): never {
  throw new Error(`Unhandled case: ${JSON.stringify(value)}`);
}

type Status = "pending" | "paid" | "shipped";

function label(status: Status): string {
  switch (status) {
    case "pending":
      return "Waiting for payment";
    case "paid":
      return "Paid";
    case "shipped":
      return "On its way";
    default:
      return assertNever(status);
  }
}

If all cases are handled, status is never in default, and the code compiles.

Now someone adds "refunded" to Status. In default, status is now "refunded", which cannot be passed to a never parameter, so you get a compile error pointing at exactly the place you forgot. This catches bugs during development instead of in production.

An alternative without a helper:

default: {
  const exhaustive: never = status;
  return exhaustive;
}

Common mistakes

  • Writing a type guard that does not really check what it claims.
  • Using as instead of a guard or assertion.
  • A default branch that silently returns something, hiding new cases.

How to say it in an interview

"A user-defined type guard returns value is T, so a true result narrows the argument; I use them to validate unknown data and in filter callbacks. An assertion function uses asserts value is T and throws on failure, narrowing everything after the call. For exhaustiveness I pass the value to an assertNever function in the switch's default branch; if a new union member is added and not handled, it is no longer never and the compiler flags it."

Key words

WordMeaning
Type guard functionReturns value is T to narrow on true
Type predicateThe value is T return type
Assertion functionThrows if a check fails; narrows afterwards
Exhaustive checkProving every case of a union is handled
assertNeverA helper that only accepts never

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.