QA Interview Hub · Knowledge base · Quizzes · Українська

TypeScript › Type narrowing and type guards

User-defined type guards and assertion functions

A type guard is a function returning value is T; when it returns true, the compiler narrows the variable to T. An assertion function with asserts value is T throws on failure and narrows the type afterwards. The compiler does not verify that the body really proves T, so an incomplete guard gives a wrong type silently. For API responses prefer a schema that infers the type.

TypeScript · Narrowing

A guard says true for an object with a string balance and the compiler believes it. Who checks the checker?

An API response arrives as unknown and the compiler has to be convinced it is an Account. Built-in checks are not enough, so the automation engineer writes a custom guard function. It is handy, but has a weak spot: the compiler does not verify its body. A wrong function gives a wrong type, and the error shows up far from the cause. The lesson covers guard functions, assertion functions and when to replace them with a schema.

How it works and why. A type guard is a function with the return type value is T (a type predicate). For the compiler it is a contract: if the function returned true, the variable has type T in the if branch; if false, T is excluded from the type in the else branch. The compiler does not look into the function body, since types have no access to execution logic. It trusts the signature, just as it trusts as. The difference is that a guard is written and tested once, while as is scattered through the code. An assertion function with asserts value is T returns nothing and throws instead, and after its call the type is narrowed for the rest of the scope.

interface Account { id: string; balance: number; currency: string }

1function isAccount(v: unknown): v is Account {
  if (typeof v !== 'object' || v === null) return false;
2  const o = v as Record<string, unknown>;
  return (
3    typeof o.id === 'string' &&
    typeof o.balance === 'number' &&
    typeof o.currency === 'string'
  );
}
  1. The predicate v is Account: the compiler will believe it without checking the body.
  2. The only as merely lets the code read properties of an already checked object as unknown: it does not promise the result type.
  3. Every field is checked separately. A forgotten field means a wrong type further in the code.

Example: a guard that lies. A simplified guard that checks only that a field exists lets wrong data through:

function isAccount(v: unknown): v is Account {
  return typeof v === 'object' && v !== null && 'id' in v;
}

const body: unknown = await res.json(); // { id: "1", balance: "100" }
if (isAccount(body)) {
  body.balance.toFixed(2); // compiles, TypeError at runtime
}

A guard or a schema

Wrong

An incomplete guard

Lets balance as a string through. The type says number, the runtime throws TypeError far from the check.

Right

A full guard or a schema

All fields are checked, and in a schema the type and the check come from one description and cannot drift apart.

Figure 1. The compiler believes the guard, so the quality of the check rests on the author.

There are two fixes. A full guard, as above, suits small types. For API response models a schema is better: it checks data at runtime, says exactly what is wrong, and defines the type from one description.

import { z } from 'zod';

const AccountSchema = z.object({
  id: z.string(),
  balance: z.number(),
  currency: z.string(),
});
type Account = z.infer<typeof AccountSchema>;

const acc = AccountSchema.parse(await res.json());
acc.balance.toFixed(2); // Account, verified at runtime

Assertion functions are handy in tests for values that must exist, where absence is a test failure. They throw with a clear message and remove the need for ? and !:

function assertDefined<T>(v: T, msg: string): asserts v is NonNullable<T> {
  if (v === undefined || v === null) throw new Error(msg);
}

function assert(cond: unknown, msg: string): asserts cond {
  if (!cond) throw new Error(msg);
}

const row = rows.find((r) => r.txId === id);
assertDefined(row, 'transaction ' + id + ' not found');
row.amount; // no ? and no !

There is a technical restriction: for a call to an assertion function to narrow the type, it must be declared with an explicit annotation. This works for a function and for a variable with an explicitly stated type, but an arrow function without an annotation causes a compiler error. Separately about arrays: a guard predicate in filter removes undefined from the result type.

const found: (Row | undefined)[] = ids.map((id) => byId.get(id));

// an explicit predicate
const rows1 = found.filter((r): r is Row => r !== undefined);

// since TypeScript 5.5 the predicate is inferred in simple cases
const rows2 = found.filter((r) => r !== undefined);

Limits and alternatives. A guard fits narrow, well-known shapes: checking an error with a code, checking a DOM element. When the shape is large or changes together with the API, a hand-written function becomes a burden: it has to be updated next to the type, and a mismatch lights up nowhere. A schema (zod, valibot, ajv) solves that and adds an error message. One more trap: a guard that wrongly returns false can narrow the else branch incorrectly, so any mistake in a predicate does harm in both directions.

Common mistakes.

  • A guard that checks only some fields: the type promises more than is guaranteed.
  • A guard function nobody tested: its bug hides behind a green compile.
  • Writing as Account instead of a guard: there is no check at all.
  • An assertion function as an arrow whose variable has no type annotation: the call does not compile (TS2775).

Check yourself

The guard isAccount checks only typeof o.id === 'string' and returns v is Account. What happens with the object { id: '1' } and where does the problem show up?

Answer

The guard returns true and the compiler treats the object as Account. There is no balance, so body.balance.toFixed(2) compiles and fails at runtime: the error is far from the check.

How does an assertion function asserts v is T differ from a guard v is T in use?

Answer

A guard returns a boolean and is put in an if; an assertion function returns nothing and throws, and the type is narrowed after the call without an if. For values that must exist in a test it is a short way to narrowing with a good message.

In an interview. Junior: A type guard is a function with value is T: after it TypeScript narrows the type. An assertion function with asserts throws and narrows the type further down the code. Middle/Senior: The compiler does not check a guard body, so an incomplete check gives a wrong type with no warning. For API responses I use a schema from which the type is derived, and keep guards and assertions for narrow checks in tests.

More articles in this chapter