Skip to content
jshacks.dev
TypeScript

Type Guards and the is Keyword

A type guard is a function that narrows a type when it returns true. Learn the is keyword, type predicates, their pitfalls and how to test a guard.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the TypeScript, Vite, Node.js and JavaScript logos.

A value that can be one of several types is only useful once the program knows which one it holds. TypeScript calls the checks that settle the question type guards, and it follows them through your control flow, so that inside an if the variable has a narrower type than it had outside. The built-in checks such as typeof and instanceof cover primitives and classes. For everything else you write your own guard, a function whose return type uses the is keyword. This post shows how type predicates work, what the compiler reports without them, where hand-written guards go wrong, and how to test them. It uses TypeScript 6.x, and the rules are described in the narrowing chapter of the handbook.

The problem a guard solves

When a parameter is a union, the compiler allows only the operations that every member supports. Code that is correct for one member is rejected until you prove which member you have.

describe.tsTypeScript
function describe(value: string | number): string {
  return value.toFixed(2);
}
Text
describe.ts(2,16): error TS2339: Property 'toFixed' does not exist on type 'string | number'.
  Property 'toFixed' does not exist on type 'string'.

The second line of the message is the useful one. It names the member that breaks the rule, which here is string. The compiler is not guessing about runtime. It is saying that on one branch of the union the property is missing, so the call is unsafe on that branch. A guard is how you tell it which branch you are on.

Built-in guards: typeof, instanceof and in

The simplest guards are expressions the compiler already understands. A typeof check narrows to a primitive, instanceof narrows to a class, and in narrows to the union members that declare a property.

builtin.tsTypeScript
function describe(value: string | number): string {
  if (typeof value === "number") {
    return value.toFixed(2);
  }
  return value.toUpperCase();
}

console.log(describe(3.14159));
console.log(describe("ready"));
Text
3.14
READY

Inside the if, value is number. After the if returns, the compiler knows the number case is gone and treats value as string. That second step is easy to miss: narrowing does not only apply within a block, it also removes types from whatever flows past an early return. Reading the code from top to bottom, each check subtracts a possibility.

The same mechanism works with classes. After error instanceof TypeError, the variable has that class's members, and the in operator narrows a union of object types by property name, as in "meow" in pet.

Writing your own guard with is

The built-in checks stop working when the test is not a single expression. Suppose you want to ask whether a value is a well-formed order, which needs several property checks. You move the check into a function and tell the compiler what a true result means with a type predicate, written parameter is Type in place of a return type.

order-guard.tsTypeScript
type Order = { id: string; total: number };

function isOrder(value: unknown): value is Order {
  return (
    typeof value === "object" &&
    value !== null &&
    typeof (value as { id?: unknown }).id === "string" &&
    typeof (value as { total?: unknown }).total === "number"
  );
}

const input: unknown = JSON.parse('{"id":"A-100","total":42}');

if (isOrder(input)) {
  console.log(input.id, input.total);
} else {
  console.log("not an order");
}
Text
A-100 42

At runtime the guard is an ordinary function returning a boolean. The predicate in its signature is the only part the compiler uses. When the call returns true, the argument is narrowed to Order in that branch. When it returns false, the argument is narrowed to whatever remains, which for unknown is still unknown. Without the predicate, the function would be typed as returning boolean, and the compiler would learn nothing from the call.

without-predicate.tsTypeScript
function looksLikeOrder(value: unknown): boolean {
  return typeof value === "object" && value !== null && "id" in value;
}

const input: unknown = JSON.parse('{"id":"A-100","total":42}');

if (looksLikeOrder(input)) {
  console.log(input.id);
}
Text
without-predicate.ts(8,23): error TS18046: 'input' is of type 'unknown'.

The check is identical in spirit, but the return type boolean discards the conclusion. This is the difference the is keyword makes: it turns a boolean result into narrowing information.

Guards that narrow both ways

A predicate narrows in the false branch as well. If the argument is a union, the else branch gets the members that are not the predicate type. That makes a guard the natural way to split a union that has no discriminating property.

pets.tsTypeScript
type Cat = { meow(): string };
type Dog = { bark(): string };

function isCat(pet: Cat | Dog): pet is Cat {
  return "meow" in pet;
}

const pets: Array<Cat | Dog> = [
  { meow: () => "mew" },
  { bark: () => "woof" },
];

for (const pet of pets) {
  if (isCat(pet)) {
    console.log(pet.meow());
  } else {
    console.log(pet.bark());
  }
}
Text
mew
woof

In the else branch, pet is Dog, because the only other member of the union is Dog. You did not write a second guard. The compiler subtracted Cat from Cat | Dog for you.

Filtering arrays with a guard

Array methods lose type information unless the callback is a guard. filter has an overload that accepts a type predicate and returns an array of the narrowed type. This is where a reusable generic guard pays off.

present.tsTypeScript
function isPresent<T>(value: T | null | undefined): value is T {
  return value !== null && value !== undefined;
}

const names: Array<string | null> = ["Ada", null, "Grace"];
const present = names.filter(isPresent);

console.log(present.map((name) => name.toUpperCase()));
Text
[ 'ADA', 'GRACE' ]

The type of present is string[], and the map callback may call a string method without a check. Using names.filter(Boolean) would leave the element type as string | null, because Boolean is not a type predicate. Since TypeScript 5.5 the compiler can also infer a predicate for simple arrow functions such as (name) => name !== null, as described in the 5.5 release notes. An explicit guard remains the clearer choice for anything you reuse.

A guard can lie

The compiler trusts the predicate completely. It does not check that the function body matches the claim, so a wrong body produces a wrong type with no warning.

liar.tsTypeScript
function isString(value: unknown): value is string {
  return typeof value === "string" || typeof value === "number";
}

const input: unknown = 7;

if (isString(input)) {
  console.log(input.toUpperCase());
}
Text
TypeError: input.toUpperCase is not a function

The code compiles cleanly, because input is a string as far as the compiler knows. The failure arrives at runtime, and the stack points at the call and not at the guard that caused it. This is the same trade as a type assertion: you have promised something the compiler cannot verify. The difference is that a guard centralises the promise in one function, so there is one place to review and one place to test.

Two common mistakes produce lying guards. One is a check that is too loose, as above. The other is a check that is correct for the cases you thought of and wrong for a case you did not, such as an object that has the right keys with the wrong value types. Check every property the type declares, not only the one you happen to read.

Testing a guard

Because a guard is a pure function, it is easy to test, and the tests are worth writing because the compiler will not catch a mistake in the body. Put in the values that should pass, and then the values that nearly pass.

order-guard.test.tsTypeScript
import { strictEqual } from "node:assert/strict";
import { isOrder } from "./order-guard.js";

strictEqual(isOrder({ id: "A-1", total: 10 }), true);
strictEqual(isOrder({ id: "A-1" }), false);
strictEqual(isOrder({ id: 1, total: 10 }), false);
strictEqual(isOrder(null), false);
strictEqual(isOrder("A-1"), false);

console.log("guard cases passed");
Text
guard cases passed

The near misses are the valuable cases: a missing property, a property of the wrong type, null, which is an object according to typeof, and a primitive. These are the inputs a loose guard accepts. If you keep a guard next to the type it describes, a change to the type is a reminder to change the guard and its tests together.

Guards on methods and assertion variants

Predicates can also describe this. A method declared with this is Type narrows the object it is called on, which is how a class can offer isAdmin() and have the compiler treat the receiver as an admin afterwards. The predicate form with asserts is a separate feature that throws instead of returning a boolean, and it is covered in the post on assertion functions. For a union with a shared literal property, a discriminated union needs no guard function at all, because a comparison such as shape.kind === "circle" narrows directly.

When not to write one

A guard is the right tool at a boundary where data arrives untyped, such as parsed JSON, a message from another window, or a record from storage. Inside well-typed code it is usually a sign that the types could be shaped better. If you find yourself guarding between two members of a union that your own code created, add a discriminating property and compare it. If the shape is large, a hand-written guard becomes a long and fragile function, and a schema validation library that returns a typed result is easier to keep correct.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.