← TypeScript

Intermediate · 4 of 16 · 14 min read

Type guards and predicates

Teaching the compiler a check it cannot work out for itself — the value is T predicate, assertion signatures, and why a wrong guard is as dangerous as a cast.

  • Type guards

The compiler narrows from checks it recognises — typeof, in, instanceof. When the check is yours, you have to tell it what a true result means. That is what a type predicate is.

Without a predicate, nothing narrows

type Car = { drive: () => void };
type Bike = { ride: () => void };

function looksLikeCar(vehicle: Car | Bike): boolean {
  return "drive" in vehicle;
}

function use(vehicle: Car | Bike) {
  if (looksLikeCar(vehicle)) {
    // vehicle.drive(); // Property 'drive' does not exist on type 'Bike'
  }
}

The function returns a boolean, and a boolean tells the compiler nothing about the argument. One word fixes it:

type Car = { drive: () => void };
type Bike = { ride: () => void };

function isCar(vehicle: Car | Bike): vehicle is Car {
  return "drive" in vehicle;
}

function use(vehicle: Car | Bike) {
  if (isCar(vehicle)) vehicle.drive();  // Car
  else vehicle.ride();                   // Bike
}

use({ drive: () => console.log("driving") });

The else is narrowed too: a predicate removes the type from the union on the false branch as well.

The compiler takes your word for it

function isCarBadly(vehicle: Car | Bike): vehicle is Car {
  return true;   // no complaint from the compiler
}

That compiles. A predicate is an assertion about the body that nothing checks, which makes a careless guard exactly as dangerous as as — with the added problem that it looks safe at every call site.

Guarding unknown

The common case, and the one with the most steps. A guard over data from outside has to check the ground it stands on:

interface User { id: number; name: string }

function isUser(value: unknown): value is User {
  return (
    typeof value === "object" &&          // 1. is it an object...
    value !== null &&                      // 2. ...and not null
    "id" in value &&
    typeof (value as User).id === "number" && // 3. and are the types right
    "name" in value &&
    typeof (value as User).name === "string"
  );
}

const parsed: unknown = JSON.parse('{"id":1,"name":"Ana"}');
if (isUser(parsed)) console.log(parsed.name.toUpperCase()); // "ANA"

console.log(isUser(null), isUser({ id: "1", name: "Ana" })); // false false

Three checks, and people routinely write only the third. "name" in value alone says the key exists, not that it holds a string — and typeof value === "object" alone lets null through.

Once the shape has more than a few fields this is clearly the wrong place to be hand-writing code, which is the argument for a schema library:

// What a schema library does for you, roughly:
//   const User = z.object({ id: z.number(), name: z.string() });
//   type User = z.infer<typeof User>;        // the type comes from the schema
//   const user = User.parse(await res.json()); // throws, or returns a User

The important part is not the library — it is that the type is derived from the check rather than declared alongside it, so the two cannot drift.

Assertion signatures

A predicate answers a question. An assertion states a fact and throws if it is false, narrowing everything after the call rather than inside an if:

function assertIsString(value: unknown): asserts value is string {
  if (typeof value !== "string") throw new TypeError("expected a string");
}

function shout(value: unknown) {
  assertIsString(value);
  return value.toUpperCase(); // narrowed from here on
}

console.log(shout("ok")); // "OK"

There is also the bare form, which narrows out the falsy values:

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

function load(id: number | undefined) {
  assert(id !== undefined, "id is required");
  return id.toFixed(0); // id is number
}

console.log(load(1)); // "1"
Predicate Assertion
Signature v is T asserts v is T
Returns boolean nothing
Narrows inside the if the rest of the scope
On failure you handle it it throws
Natural use a branch per case validation at a boundary

One restriction worth knowing: an assertion function needs an explicit type annotation at its declaration, so it cannot be a const arrow without one.

// const bad = (v: unknown): asserts v is string => {};
// Assertions require every name in the call target to be declared with an
// explicit type annotation.

const ok: (v: unknown) => asserts v is string = (v) => {
  if (typeof v !== "string") throw new TypeError("nope");
};
console.log(typeof ok);

Narrowing an array

filter only narrows when its callback is a predicate, which is why the obvious thing does not work:

const values: (string | undefined)[] = ["a", undefined, "b"];

const stillWide = values.filter(Boolean);   // (string | undefined)[]

const isDefined = <T>(value: T | undefined): value is T => value !== undefined;
const narrowed = values.filter(isDefined);  // string[]

console.log(narrowed.map((s) => s.toUpperCase())); // ["A", "B"]

Boolean is typed (value: unknown) => boolean, so it carries no narrowing information. A one-line generic predicate is the standard fix, and worth keeping in a utilities file.

The same trick picks one member out of a discriminated union:

type State = { ok: true; data: string } | { ok: false; error: string };

const isOk = (s: State): s is Extract<State, { ok: true }> => s.ok;

const states: State[] = [{ ok: true, data: "x" }, { ok: false, error: "y" }];
console.log(states.filter(isOk).map((s) => s.data)); // ["x"]

Guards on a class

A this-based predicate narrows the instance itself, which models “this object becomes usable once it is ready”:

interface Loaded { data: string }

class Resource {
  data?: string;

  load() { this.data = "ready"; return this; }

  isLoaded(): this is Resource & Loaded {
    return this.data !== undefined;
  }
}

const resource = new Resource().load();
if (resource.isLoaded()) console.log(resource.data.toUpperCase()); // "READY"

Common mistakes

A predicate whose body does not check what it claims

Mistake. return typeof value === "object" for value is User. Why it fails. Every object passes, including null before the null check and {} after it. The compiler believes the signature, so the failure surfaces wherever a property is read. What to do instead. Check each property you declared, or derive the guard from a schema.

Using in on an unknown

Mistake. return "name" in value where value: unknown. Why it fails. in needs an object, and unknown is not one yet — the body does not compile. What to do instead. Narrow to an object first: typeof value === "object" && value !== null.

filter(Boolean) to remove the nullables

Mistake. Expecting (string | undefined)[] to become string[]. Why it fails. Boolean’s signature returns boolean, not a predicate, so nothing narrows. What to do instead. A small generic isDefined predicate, used as the callback.

Check yourself

4 questions from the bank on what you just read. Answering here does not affect your quiz history.

What does the return type value is Car do on a function?

A guard over data that came from outside has to check the ground it stands on.

What is wrong with this guard for parsed JSON?

Code sample
function isUser(value: unknown): value is { name: string } {
  return "name" in value;
}

What does an assertion signature — asserts value is string — do differently from a predicate?

Why does array.filter(Boolean) not narrow out the undefined?

Practise Type guards →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.