Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

TypeScript Type Narrowing: Type Guards, in Operator, and Discriminated Unions

Every guard TypeScript uses to narrow a union, what each one removes, and the three failures that keep narrowing from applying: typeof null, widened discriminants, and closures over mutable bindings.

~6 min readTypeScript
#TypeScript#Type System#Web Development
Union type values funneled through type guard gates into separate Admin, Guest, and null streams

Narrowing is the compiler's record of what a value can still be at one particular line. A union such as string | number | null is not narrowed once and for all by declaring it; the type shrinks statement by statement as checks pass, and it widens back the moment control flow leaves the branch that proved the check. Every guard in this article — typeof, in, instanceof, equality, custom predicates, and the discriminant property of a tagged union — is a different way of telling that same analysis which members remain possible.

Quick Summary

  • Narrowing is a property of a position in the code, not of the variable. Move the check into another function, or a callback, and the narrowing usually does not follow.
  • typeof x === "string" narrows to the primitive string type, but typeof x === "object" also matches null and arrays, so it never gives you a clean object type on its own.
  • Truthiness checks (if (x)) remove null, undefined, 0, "", NaN, and false at once, which is right for objects and wrong for numbers and strings.
  • "prop" in obj narrows by property presence, not by value, and since TypeScript 4.9 it also narrows objects whose declared type does not list that property.
  • A discriminated union is only as good as its discriminant: it must be a literal type, it must be present on every member, and the exhaustive switch needs a never sink to fail compilation when a new member appears.
  • A user-defined predicate (value is T) is a promise, not a proof. The compiler checks that the predicate type is assignable to the parameter type and then trusts the body completely.

Basic syntax and type signatures

typescript
// Built-in guards: the compiler knows these by their syntax. function format(value: string | number | null): string { if (value === null) return "-"; // null removed if (typeof value === "number") { return value.toFixed(2); // string removed } return value.trim().toUpperCase(); // number and null removed } // in operator narrows by property presence. type Admin = { role: "admin"; permissions: string[] }; type Guest = { role: "guest"; expiresAt: Date }; function describe(user: Admin | Guest): string { if ("permissions" in user) { return `admin with ${user.permissions.length} scopes`; } return `guest until ${user.expiresAt.toISOString()}`; } // Discriminated union: one literal property separates the members. type Shape = | { kind: "circle"; radius: number } | { kind: "square"; side: number } | { kind: "rect"; width: number; height: number }; function area(shape: Shape): number { switch (shape.kind) { case "circle": return Math.PI * shape.radius ** 2; case "square": return shape.side ** 2; case "rect": return shape.width * shape.height; default: { const exhaustive: never = shape; // compile error when a member is added return exhaustive; } } } // User-defined predicate: the return type is `value is T`. function isNonEmptyString(value: unknown): value is string { return typeof value === "string" && value.length > 0; }

The signature (value: unknown) => value is string is what makes the call narrow at the call site. The body is ordinary code and is not verified against the claim: return true would satisfy the compiler and narrow every caller to string. That asymmetry is the single most important thing to understand about custom guards, and it is why they belong in one small, tested module rather than scattered across a codebase.

Assertion functions are the statement form of the same idea:

typescript
function assertIsDefined<T>(value: T): asserts value is NonNullable<T> { if (value === null || value === undefined) { throw new Error("Expected a defined value"); } } function handle(input: string | undefined) { assertIsDefined(input); // control flow narrows from here on return input.length; }

asserts requires the called function to have an explicit type annotation at the call site; const check = assertIsDefined; check(x) does not narrow, because an unannotated alias has no assertion signature to read (TS2775).

Narrowing constructs side by side

ConstructWhat it narrowsRemoves too muchTrust boundary
typeof x === "string"primitives and functionsnothing, but "object" keeps null and arrayscompiler
x === null / x !== undefinedexact nullish membernothingcompiler
if (x) truthinessnullish plus falsy primitives0, "", NaN, falsecompiler
x instanceof Dateto the class and its base typesonly null/undefined on the negative sidecompiler (class identity)
"k" in xadds/removes members by propertymembers with optional k?: T are all kept on the positive sidecompiler
x.kind === "circle"the member with that literal discriminantnothingcompiler, if kind is a literal union
x is T predicateto Twhatever the body decidesthe author of the function
x as Tto Tany member at allnobody — it is an assertion

The vertical order matters: everything above the last two rows is checked, everything below is declared. A code review that asks "where did this type come from" is really asking which of these two halves of the table produced it.

Practical edge cases and deep dives

1. typeof null, arrays, and the object guard everyone writes wrong

typescript
function isPlainObject(value: unknown): value is Record<string, unknown> { return typeof value === "object" && value !== null && !Array.isArray(value); }

typeof null is "object" in JavaScript because of a 1995 representation detail, so the null check is mandatory before any property access. Arrays are objects too, so typeof [] === "object" passes; if the function accepts arrays, Array.isArray must come first, because once the value is narrowed to Record<string, unknown> the array element type is gone and Array.isArray no longer informs the compiler. Boxed primitives (new String("x")) are objects as well, and functions are "function", not "object", even though they are objects at runtime:

typescript
function kindOf(value: unknown): string { if (value === null) return "null"; if (Array.isArray(value)) return "array"; if (typeof value === "function") return "function"; return typeof value; // "object" | "string" | "number" | ... }

2. in narrowing and the optional-property trap

typescript
type WithId = { id: string; name?: string }; type WithSlug = { slug: string }; function keyOf(entity: WithId | WithSlug) { if ("id" in entity) { return entity.id; // WithId } return entity.slug; // WithSlug }

The positive branch keeps every member that could have an id, so a member declared id?: string is not excluded, and the narrowed type there is WithId. If the union contains a member with the same key at a different type ({ id: number }), in does not disambiguate by runtime type: the narrowed type is the intersection of both candidates, and reading entity.id yields string & number, which is never — the code compiles but cannot do anything with the value.

TypeScript 4.9 relaxed the other half of the rule: when the declared type is a single object type (not a union) that does not list the key, "k" in x now narrows to T & Record<"k", unknown> instead of leaving the type unchanged. That is what makes guards over object or unknown worth writing without a cast:

typescript
function hasMessage(value: unknown): value is { message: string } { return typeof value === "object" && value !== null && "message" in value && typeof (value as { message?: unknown }).message === "string"; }

The assertion inside is unavoidable here: after "message" in value the key exists at type level with type unknown, and comparing an unknown against "string" with typeof is allowed, so typeof value.message === "string" also works without the cast as long as value is already an object type. Keeping the in check and the typeof check on separate lines is what lets each one narrow before the next runs.

3. Exhaustiveness that survives the next teammate

The never sink in the switch above fails compilation the moment a new member joins Shape, and that is the point: the error appears where the decision has to be made, not in production. Two details make it work reliably.

typescript
function assertNever(value: never, message = "Unexpected variant"): never { throw new Error(`${message}: ${JSON.stringify(value)}`); } type Event = | { type: "click"; x: number; y: number } | { type: "key"; code: string } | { type: "scroll"; delta: number }; function handle(event: Event): string { switch (event.type) { case "click": return `${event.x},${event.y}`; case "key": return event.code; case "scroll": return `${event.delta}`; } return assertNever(event); // TS2345 until "scroll" was handled }

First, the discriminant must be a literal type, not string. type: string makes every case comparison legal and the union stops discriminating — every member stays in scope in every branch, and the never sink reports the whole union instead of never. Second, exhaustiveness only holds when the compiler can see the closing branch as unreachable; a default: that returns a fallback string silently absorbs new members, which is a perfectly good choice for resilient UIs and a bug factory for dispatch tables that must stay complete.

4. Narrowing does not survive a callback

typescript
function first(items: (string | null)[]) { const head = items[0]; if (head === null) return ""; // Narrowed: head is string here. const read = () => head.length; // still string: head is const let mutable: string | null = head; if (mutable !== null) { const later = () => mutable.length; // TS18047: mutable is possibly null mutable = null; return later(); } return read(); }

The rule is about when the value could change. A const binding cannot be reassigned, so a narrowing on it is preserved inside closures. A let or a property (this.state.value) can be reassigned by any call, so TypeScript discards the narrowing inside a nested function — and, for properties, after any function call, because the call could have mutated the object. The fix is to copy into a const before closing over it; that is also the fix that removes the actual race, not just the type error.

Common mistakes and compiler errors

ErrorMessageCauseFix
TS2339Property does not exist on type neverthe exhaustive sink is being read, or a union member was already eliminateduse assertNever, or delete the dead branch
TS2367This comparison appears to be unintentional because the types have no overlapcomparing against a value the narrowed type cannot holdcheck the order of guards, or the literal spelling
TS18047x is possibly nullnarrowing lost inside a closure over a letcopy into a const first
TS2775Assertions require every name in the call target to be declared with an explicit type annotationassertion function called through an aliasannotate the alias, or call the function directly
TS2677A type predicate's type must be assignable to its parameter's typeis T where T is wider than the parameterwiden the parameter, or narrow the predicate
TS2345Argument of type X is not assignable to parameter of type nevera variant is unhandled in the exhaustive callhandle the missing case
TS2322Type string is not assignable to type "circle"discriminant widened to stringdeclare the property as a literal union, or use a const object

The failure mode behind most of these rows is the same: the type was narrowed by an assumption (a cast, a predicate, a widened literal) rather than by a check the compiler can re-derive. When a narrowing stops working after a refactor, look first at whether the guard moved into a function whose return type is boolean instead of a predicate — a plain boolean return gives the caller nothing, while value is T carries the information back across the boundary.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.