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.

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, buttypeof x === "object"also matchesnulland arrays, so it never gives you a clean object type on its own.- Truthiness checks (
if (x)) removenull,undefined,0,"",NaN, andfalseat once, which is right for objects and wrong for numbers and strings. "prop" in objnarrows 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
switchneeds aneversink 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
// 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:
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
| Construct | What it narrows | Removes too much | Trust boundary |
|---|---|---|---|
typeof x === "string" | primitives and functions | nothing, but "object" keeps null and arrays | compiler |
x === null / x !== undefined | exact nullish member | nothing | compiler |
if (x) truthiness | nullish plus falsy primitives | 0, "", NaN, false | compiler |
x instanceof Date | to the class and its base types | only null/undefined on the negative side | compiler (class identity) |
"k" in x | adds/removes members by property | members with optional k?: T are all kept on the positive side | compiler |
x.kind === "circle" | the member with that literal discriminant | nothing | compiler, if kind is a literal union |
x is T predicate | to T | whatever the body decides | the author of the function |
x as T | to T | any member at all | nobody — 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
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:
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
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:
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.
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
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
| Error | Message | Cause | Fix |
|---|---|---|---|
| TS2339 | Property does not exist on type never | the exhaustive sink is being read, or a union member was already eliminated | use assertNever, or delete the dead branch |
| TS2367 | This comparison appears to be unintentional because the types have no overlap | comparing against a value the narrowed type cannot hold | check the order of guards, or the literal spelling |
| TS18047 | x is possibly null | narrowing lost inside a closure over a let | copy into a const first |
| TS2775 | Assertions require every name in the call target to be declared with an explicit type annotation | assertion function called through an alias | annotate the alias, or call the function directly |
| TS2677 | A type predicate's type must be assignable to its parameter's type | is T where T is wider than the parameter | widen the parameter, or narrow the predicate |
| TS2345 | Argument of type X is not assignable to parameter of type never | a variant is unhandled in the exhaustive call | handle the missing case |
| TS2322 | Type string is not assignable to type "circle" | discriminant widened to string | declare 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 toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesTypeScript Generic Parameter Defaults: Syntax, Precedence, and Inference
When a default applies and when inference wins, defaults that reference earlier parameters, and how a defaulted type parameter keeps a library change non-breaking.
TypeScript Branded Types: Nominal Typing, Type Tags, and Validation
How a phantom property makes two strings incompatible, unique symbol brands, unit-typed numbers, and the places where a brand quietly disappears.
TypeScript Ambient Declarations: .d.ts Files, declare, and declare global
How declare and .d.ts files describe runtime values, wildcard modules for assets, declare global with var, and module augmentation of third-party types.
TypeScript Discriminated Unions: Exhaustiveness Checking and the never Type
Why the discriminant must be a literal, how never closes an exhaustive switch, and the duplicate-discriminant bug that lets a missing case compile.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.