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.

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.
function describe(value: string | number): string {
return value.toFixed(2);
}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.
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"));3.14
READYInside 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.
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");
}A-100 42At 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.
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);
}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.
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());
}
}mew
woofIn 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.
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()));[ '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.
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());
}TypeError: input.toUpperCase is not a functionThe 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.
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");guard cases passedThe 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.


