Type Guards: The Bouncer's Checklist

Type Guards: The Bouncer's Checklist in TypeScript: A members' club runs a single door onto a mixed queue.

The Analogy: The Door Supervisor's Admissions Log at a Members' Club

A members' club runs a single door onto a mixed queue. Some people in the line hold a member card, some a guest ticket for the evening, and some a staff badge for the back rooms. From the supervisor's stool at the door they all look the same: a person in the queue. Until a check is made, the only things the supervisor may act on are the things true of everyone in the line, such as "is holding some kind of pass". Anything specific to members, or specific to staff, is off limits, because the person in front might be any of the three.

The supervisor's job is to run one definite check and write the result in the admissions log. They look at the member card against the register, or read the colour of the staff wristband, and once the check passes they write "member, table 4" or "staff, kitchen" in the log. From that entry onward, everyone inside treats the person as exactly that category: the bar knows to charge member prices, the kitchen door knows to let staff through. A type guard is that check, and the log entry is what TypeScript calls narrowing. After a passing check, the compiler treats the value as the narrower type for the rest of that branch and lets you reach the fields only that type has.

The log entry holds only for as long as nothing changes. If the person hands their wristband to a friend, or steps out and the band is cut at the exit, the old entry is void and re-entry needs a fresh check at the door. The supervisor cannot rely on a stamp made an hour ago for someone who has since swapped bands. Narrowing works the same way: it is reset the moment the variable is reassigned, and it does not carry into a deferred callback over a reassignable binding, because by the time that callback runs the value may have changed. To keep a checked result safe, you copy it somewhere it cannot change.

The failure mode is a supervisor who writes "member" in the log without actually looking at the card, waving the queue through to keep it moving. The log now carries a guarantee that was never verified, and every station inside acts on it: the bar serves member prices to someone with no membership, the kitchen door opens for a stranger. Nothing downstream can tell, because they trust the log. This is exactly what a guard that returns a bare boolean, or a predicate whose body does not really check, or a blunt type assertion does: it stamps the type onto the value and the compiler believes it, so the lie surfaces only later, at runtime, far from the door where it was told.


Syntax or Core Structure

The everyday guards are the operators you already know. An equality check against null, a typeof test, and a fall-through by elimination each narrow a union so the branch below can use the type it isolated.

// src/show.ts
function show(value: string | number | null): string {
    if (value === null) {
        return "none";
    }
    if (typeof value === "string") {
        return value.trim();
    }
    return value.toFixed(2);
}

console.log(show("  hi  "));
console.log(show(3));
console.log(show(null));

Output:

hi
3.00
none

Each branch narrows what follows it. show(" hi ") is not null and typeof reports "string", so the value is a string and value.trim() gives "hi". show(3) is not null and not a string, so by elimination it is a number and value.toFixed(2) gives "3.00". show(null) takes the first branch and returns "none". The compiler lets .trim() and .toFixed(2) through only because the checks above each call proved the type.


Technical Depth: The Full Set of Checks and Where They Fail

The built-in operators cover most cases, a custom predicate handles the rest, unknown data is where guards earn their keep, and narrowing has two rules about when it is lost.

The native narrowing mechanisms

TypeScript understands a fixed set of runtime checks and narrows the type in the branch each one guards.

CheckWhat it narrows
typeof x is a primitive namestring, number, boolean, and the other primitives
x instanceof Cinstances of a class C
the "key" in obj testobject shapes that have that key
x compared to nullnullish values away from the rest
x.kind compared to a literalone arm of a discriminated union

Truthiness (if (x)) narrows too, but it discards "" and 0 along with null and undefined, so it is the wrong tool when an empty string or zero is a valid value.

instanceof narrows to a class

When one arm of a union is a class instance, instanceof is the check. It asks whether the value was built from that constructor and narrows the branch to it.

// src/kind.ts
class Note {
    constructor(public text: string) {}
}
interface Memo {
    title: string;
}

function describe(item: Note | Memo): string {
    if (item instanceof Note) {
        return "note " + item.text;
    }
    return "memo " + item.title;
}

console.log(describe(new Note("call back")));
console.log(describe({ title: "buy milk" }));

Output:

note call back
memo buy milk

describe(new Note("call back")) passes the instanceof Note test, so the branch narrows to Note and item.text is reachable, giving "note call back". The plain object fails that test, so by elimination it is a Memo and item.title gives "memo buy milk". A plain object literal is never an instance of a class, which is exactly why instanceof can tell the two arms apart.

A custom predicate with the is return type

When no built-in check fits, write a function whose return type is value is T. The boolean it returns tells the compiler, in the true branch, to narrow the argument to T.

// src/predicate.ts
interface Admin {
    role: "admin";
    scopes: string[];
}
interface Guest {
    role: "guest";
}
type Account = Admin | Guest;

function isAdmin(account: Account): account is Admin {
    return account.role === "admin";
}

function label(account: Account): string {
    if (isAdmin(account)) {
        return account.scopes.join(", ");
    }
    return "guest";
}

console.log(label({ role: "admin", scopes: ["read", "write"] }));
console.log(label({ role: "guest" }));

Output:

read, write
guest

Because isAdmin returns account is Admin, the if branch narrows the account to Admin and account.scopes is reachable, joining to "read, write". The guest falls through to "guest". Had isAdmin been declared with a plain : boolean return, the branch would still see the whole Account union and account.scopes would not compile, because Guest has no such field. The predicate is what turns a boolean into a narrowing.

Guarding unknown data at the boundary

The real payoff is at the edge of the system, where data arrives as unknown. A predicate that checks each field lets everything downstream treat the value as typed.

// src/unknownguard.ts
interface Item {
    sku: string;
    qty: number;
}

function isItem(value: unknown): value is Item {
    if (typeof value !== "object" || value === null) {
        return false;
    }
    const v = value as Record<string, unknown>;
    return typeof v.sku === "string" && typeof v.qty === "number";
}

console.log(isItem({ sku: "A1", qty: 3 }));
console.log(isItem({ sku: "A1" }));

Output:

true
false

isItem first rules out non-objects and null (recall that typeof null is "object", so the explicit null check is not optional), then verifies both fields. The complete object returns true; the one missing qty returns false because typeof undefined is not "number". A caller can now write if (isItem(data)) and read data.sku and data.qty with the compiler's blessing.

Where narrowing is lost

Narrowing is reset by any assignment to the variable, and it does not follow a reassignable let into a deferred callback. Copy the checked value into a const and the copy stays narrowed.

// src/lost.ts
function lengthLater(value: string | null): number {
    if (value === null) {
        return 0;
    }
    const fixed = value;           // copy the narrowed value into a const
    const read = () => fixed.length;
    return read();
}

console.log(lengthLater("fixed"));
console.log(lengthLater(null));

Output:

5
0

After the null check, value is a string, and copying it into the const fixed freezes that fact. The closure read captures fixed, which can never be reassigned, so fixed.length compiles and lengthLater("fixed") returns 5. Capturing the original let-like parameter directly in a closure that outlived the check would fail, because the compiler cannot prove the value is still a string by the time the callback runs. The null case returns 0 from the guard.


Real World Example: Validating a Delivery Feed

A warehouse receives a delivery feed as a list of unknown values decoded from JSON. Each entry should be a line with a reference, a quantity, and a price, but the feed is dirty: some entries are missing fields or carry the wrong type. A guard filters the feed down to the valid lines, and the report totals only what passed the door.

// src/intake.ts
interface Line {
    ref: string;
    qty: number;
    price: number;
}

function isLine(value: unknown): value is Line {
    if (typeof value !== "object" || value === null) {
        return false;
    }
    const v = value as Record<string, unknown>;
    return typeof v.ref === "string" && typeof v.qty === "number" && typeof v.price === "number";
}

function pad(text: string, width: number): string {
    return text.padEnd(width);
}

const FEED: readonly unknown[] = [
    { ref: "A1", qty: 3, price: 20 },
    { qty: 1, price: 10 },
    { ref: "B2", qty: 2, price: 45 },
    { ref: "C3", qty: 4, price: 20 },
    { ref: "D4", qty: "5", price: 30 },
];

const lines: Line[] = [];
for (const entry of FEED) {
    if (isLine(entry)) {
        lines.push(entry);
    }
}

const rows: string[] = [];
let goods = 0;
for (const line of lines) {
    const total = line.qty * line.price;
    goods += total;
    rows.push(pad(line.ref, 6) + pad(String(line.qty), 6) + pad(String(line.price), 8) + String(total));
}

const accepted = lines.length;
const rejected = FEED.length - accepted;
const report = [
    "accepted: " + accepted + ", rejected: " + rejected,
    pad("REF", 6) + pad("QTY", 6) + pad("PRICE", 8) + "LINE",
    ...rows,
    "goods: " + goods,
];
console.log(report.join("\n"));

Output:

accepted: 3, rejected: 2
REF   QTY   PRICE   LINE
A1    3     20      60
B2    2     45      90
C3    4     20      80
goods: 230

The guard is the door and the loop is the log. isLine rules out anything that is not an object with the three fields at the right types, so the entry missing ref and the entry whose qty is the string "5" are both turned away; the three well-formed entries pass and are pushed into lines, which the compiler now knows is a Line[]. That is what lets the report loop read line.qty and line.price with no cast and no complaint.

Trace the figures against the accepted lines. A1 is 3 * 20, which is 60; B2 is 2 * 45, which is 90; C3 is 4 * 20, which is 80. The goods total is 60 + 90 + 80, which is 230. Five entries arrived and three passed, so accepted is 3 and rejected is 5 - 3, which is 2, both printed in the header.

The design has real limits worth naming. The sharpest flaw is that isLine checks types, not values: a number field passes even when it is negative, or zero, or NaN -- and since typeof NaN is "number", a feed carrying price: NaN would sail through the door and poison goods, turning the whole total into NaN with no error anywhere. A sturdier guard would also assert Number.isFinite(v.price) and a non-negative qty. The second limit is that the loop drops every rejected entry silently, keeping only a count; a malformed feed and a genuinely short one produce indistinguishable output, where a real intake would record why each line was turned away. A guard tells you whether a value has the right shape; it says nothing about whether the values inside make sense.


Common Mistakes

  1. Returning boolean instead of value is T. A guard declared : boolean runs correctly at runtime but narrows nothing, so the true branch still sees the whole union and the type-specific fields will not compile. The value is T return type is what does the work.
  1. Writing a guard that lies. function isUser(v: unknown): v is User { return true; } compiles and hands every caller a guarantee that was never checked. A predicate is a promise the compiler cannot verify, so a false body is a runtime crash waiting downstream.
  1. Using as instead of a guard at a boundary. A type assertion checks nothing at runtime; it only silences the compiler. Data arriving from JSON, a network call, or storage should pass through a real guard, not be asserted into the shape you hope it has.
  1. Checking typeof x is "object" without a null test. typeof null is "object", so an object check that forgets value !== null will treat null as a valid object and crash on the first field access.
  1. Using truthiness on numbers and strings. if (count) also rejects 0, and if (name) also rejects "". When zero or the empty string is a valid value, test against null or undefined explicitly rather than for truthiness.
  1. Expecting narrowing to survive a reassignment. Any assignment to the variable resets what the compiler knows about it, so a check made before the assignment no longer holds after it. Re-check, or copy the checked value into a const.
  1. Capturing a narrowed let in a deferred callback. Narrowing does not follow a reassignable binding into a closure that runs later, because the value may change first. Copy it into a const before the callback closes over it.
  1. Checking only field presence, not field values. A shape guard that verifies types will still accept a negative quantity, an empty string, or NaN. When the values must be sane, the guard has to check them, not just their types.
  1. Relying on "key" in obj across a prototype chain. The in operator sees inherited keys as well as own ones, so use Object.hasOwn(obj, key) when only an own property should count.

Best Practices

  • Narrow with the cheapest tool that works. Reach for typeof, then instanceof, then a discriminant field, and only write a custom predicate when none of the built-ins can express the check.
  • Type boundary data as unknown and guard it. Give values from JSON, the network, or storage the type unknown and pass them through a guard, so nothing untyped leaks into the rest of the code.
  • Keep guards pure and total. A guard should have no side effects and should check every field it claims to, so callers can trust the promise its value is T return type makes.
  • Prefer a discriminated union to a structural guard. A shared kind field lets the compiler narrow for free on a literal comparison, and it survives refactors that a hand-written field-by-field guard would silently outlast.
  • Copy a narrowed value into a const before a closure. When a checked value must be used inside a callback, assign it to a const first so the narrowing cannot be undone by a later reassignment.
  • Check values, not just shapes, when it matters. Add Number.isFinite and range checks to a guard whose numbers must be sane, so a structurally valid but nonsensical payload is turned away at the door.
  • Reach for a schema validator on large payloads. For deep or repetitive shapes, a validator whose parse step acts as one big guard is less error-prone than a tower of hand-written field checks.
  • Record why a value was rejected when it matters. When a rejected entry is more than noise, return or log the reason rather than dropping it, so a malformed feed can be told apart from a short one.

Practice Exercises

  1. The predicate. Write isString(value: unknown): value is string and use it to filter [1, "a", true, "b"] down to a string[], confirming the result type is no longer the mixed union.
  1. The shape check. Build isTodo(value: unknown): value is { id: number; text: string; done: boolean } that checks all three fields and their types, and run it on the output of JSON.parse for both a valid and an invalid string.
  1. The value check. Extend isLine from the lesson so it also rejects a non-finite price and a negative qty, then feed it { ref: "X", qty: -1, price: NaN } and confirm it is turned away.
  1. The lost narrowing. Declare let name: string | null, narrow it with an if, then read name.length inside a setTimeout callback. Observe the error, then fix it by copying name into a const before the callback.