← blog
TypeScriptNovember 27, 2026 · 15 min read

TypeScript Type Narrowing: The Complete Guide

Learn how TypeScript type narrowing really works — typeof, instanceof, discriminated unions, and custom type guards — plus a copy-paste cheat sheet.

Parsa Jiravand · Frontend engineer · building bestpractic
TypeScript Type Narrowing: The Complete Guide

You write function greet(value: string | null), guard it with if (value === null) return;, and schedule a setTimeout callback that uses value. Right after scheduling it, you reset value back to null — a one-line cleanup, nothing dramatic. TypeScript suddenly reports "value is possibly null" inside the callback, on a check you already passed three lines earlier. Nothing about the check was wrong. You just ran into one of the specific, learnable rules of type narrowing, the mechanism TypeScript uses to track which members of a union type are still possible at each line of your code.

By the end of this guide you'll be able to:

  • Explain what control flow analysis actually tracks as it reads your code
  • Use typeof, instanceof, the in operator, and equality checks to narrow a union correctly
  • Model variants with discriminated unions instead of a pile of optional fields
  • Write your own type guard (x is T) and assertion functions, and know when a plain boolean function won't narrow anything
  • Recognize the specific situations where narrowing is lost — closures and repeated function calls — and fix each one, plus why a generic type parameter narrows differently rather than losing narrowing at all

Who this is for: you've written union types and if checks in TypeScript, and you've either hit a narrowing error that didn't make sense, or you want to know what the compiler is actually doing instead of treating it as a black box.

Here's the naïve version of the opening story, written out in full:

TypeScript
1
2
3
4
function shout(value: string | number | null) { return value.toUpperCase(); // Error: 'value' is possibly 'null'. // Error: Property 'toUpperCase' does not exist on type 'number'. }

value's declared type is string | number | null — a union of three possibilities. TypeScript has no way to know, at this line, which one you actually have, so it only allows operations that are valid on every member of the union. toUpperCase exists on string, not on number or null, so the call is rejected no matter which branch is "probably" true at runtime.

The tempting fix is to make the compiler stop complaining:

TypeScript
1
2
3
function shout(value: string | number | null) { return (value as string).toUpperCase(); // compiles — and crashes if value is null }

as string doesn't check anything — it tells TypeScript to trust you, and TypeScript does, even when you're wrong. This is the thing to avoid for this entire guide: a cast silences the error without resolving the uncertainty it was reporting.

The real fix is to narrow the union — write a check whose outcome TypeScript can use to rule members out:

TypeScript
1
2
3
4
function shout(value: string | number | null) { if (typeof value !== "string") return; return value.toUpperCase(); // value: string here — no cast needed }

Nothing about value's declared type changed. What changed is TypeScript's belief about which members of that union are still possible at this specific line, given the typeof check that just ran and returned early.

The mental model: as TypeScript reads your function from top to bottom, it maintains a type for every variable at that exact point in the code — not one fixed type for the whole function. This per-line tracking is called control flow analysis. Every if, else, return, throw, &&, ||, and switch forks that tracking into branches, and every point where branches rejoin (the line after an if block, say) merges the types back together as a union of whatever each branch produced.

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function example(value: string | number | null) { // value: string | number | null if (value === null) { // value: null return; } // value: string | number (the null branch returned, so it's gone) if (typeof value === "string") { // value: string } else { // value: number (the only thing left once string is ruled out) } // value: string | number (merged back after the if/else) }

Key concept: narrowing is not a special annotation you add — it's TypeScript running the same reasoning you would, mechanically, on every condition in your code, and remembering the result line by line.

typeof narrows unions of primitives — string, number, boolean, bigint, symbol, undefined, function, and object:

TypeScript
1
2
3
4
5
6
function format(value: string | number) { if (typeof value === "number") { return value.toFixed(2); // value: number } return value.trim(); // value: string }

Truthiness narrowing uses any value in boolean position — an if, a &&, a ternary — and rules out the falsy members of a union (null, undefined, "", 0, false, NaN) that the type can represent, not every falsy value of the remaining type:

TypeScript
1
2
3
4
5
function printLength(value: string | null | undefined) { if (value) { console.log(value.length); // value: string — null and undefined are ruled out } }

Watch the gap here: if (value) also excludes the empty string "", which is a perfectly valid string. Truthiness narrowing removes null | undefined from the type, but it does not mean "every string reached this branch" — an empty string never gets here at runtime either. For that reason, prefer an explicit check when the empty string matters:

TypeScript
1
2
3
if (value !== null && value !== undefined) { console.log(value.length); // value: string, including "" }

Equality narrowing uses ===, !==, ==, and != against a specific value or another variable, and also works inside a switch:

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
type Status = "idle" | "loading" | "success" | "error"; function describe(status: Status) { switch (status) { case "idle": return "Not started"; // status: "idle" case "error": return "Something went wrong"; // status: "error" default: return "In progress"; // status: "loading" | "success" } }

instanceof narrows by checking the prototype chain — the standard way to distinguish classes, including the built-in Error hierarchy:

TypeScript
1
2
3
4
5
6
7
8
9
10
async function load(url: string) { try { return await fetch(url); } catch (err) { if (err instanceof TypeError) { console.error("Network failure:", err.message); // err: TypeError } throw err; } }

This matters because a catch clause's variable is typed unknown by default in modern TypeScript (useUnknownInCatchVariables) — you're required to narrow it, with instanceof or typeof, before touching .message or anything else on it.

The in operator narrows object unions by checking whether a property exists, which is the tool to reach for when the members aren't class instances:

TypeScript
1
2
3
4
5
6
7
8
9
10
type Dog = { bark(): void }; type Cat = { meow(): void }; function speak(animal: Dog | Cat) { if ("bark" in animal) { animal.bark(); // animal: Dog } else { animal.meow(); // animal: Cat } }

This is the single most important pattern in this guide. Instead of one type with several optional fields — which lets you construct impossible combinations and gives in/typeof nothing clean to check — give every variant a shared, literal-typed property (the discriminant) and let the value of that one property select the whole shape:

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// the shape that invites bugs: are width/height and radius ever both set? neither? type BadShape = { kind: "circle" | "rectangle"; radius?: number; width?: number; height?: number; }; // the discriminated union: each variant is its own exact type type Circle = { kind: "circle"; radius: number }; type Rectangle = { kind: "rectangle"; width: number; height: number }; type Shape = Circle | Rectangle; function area(shape: Shape) { switch (shape.kind) { case "circle": return Math.PI * shape.radius ** 2; // shape: Circle — width/height don't exist here case "rectangle": return shape.width * shape.height; // shape: Rectangle } }

Checking shape.kind against a specific literal narrows shape itself to the one member of the union whose kind field has that literal type — this works because every variant's discriminant is a distinct literal, not the general string. Add a default branch that returns shape satisfies never (or assigns shape to a variable typed never) and the compiler will flag any future variant you forget to handle — that's exhaustiveness checking, a direct payoff of narrowing a discriminated union down to nothing, worth its own guide.

Runs right in your browser — poke at it and watch the concept react live.

Sometimes the check you need isn't typeof, instanceof, or in — it's custom logic. A plain function returning boolean does not narrow, even if it's correct at runtime:

TypeScript
1
2
3
4
5
6
7
8
9
function isString(value: unknown): boolean { return typeof value === "string"; } function example(value: string | number) { if (isString(value)) { value.toUpperCase(); // Error: 'toUpperCase' does not exist on type 'string | number' } }

TypeScript doesn't inline the function to see what it checks — it only looks at the declared return type, and boolean carries no information about value. The fix is a type predicate, written as parameterName is Type in the return position:

TypeScript
1
2
3
4
5
6
7
8
9
function isString(value: unknown): value is string { return typeof value === "string"; } function example(value: string | number) { if (isString(value)) { value.toUpperCase(); // value: string — the predicate narrows it } }

Key concept: value is string is a promise you're making to the compiler about what a true result means. TypeScript trusts the annotation, not the implementation — write the check carefully, because a wrong predicate narrows to the wrong type with no error.

Assertion functions (TypeScript 3.7+) are the assert-style sibling: instead of returning a boolean to branch on, they throw when the condition fails, and everything after the call is narrowed for the rest of the scope:

TypeScript
1
2
3
4
5
6
7
8
9
10
function assertIsString(value: unknown): asserts value is string { if (typeof value !== "string") { throw new Error("Expected a string"); } } function example(value: string | number) { assertIsString(value); value.toUpperCase(); // value: string — narrowed for the rest of this scope, no if needed }

Narrowing is lost inside a closure if the variable can be reassigned. TypeScript can't know when a nested function will actually run, so if the outer variable is reassigned anywhere in the enclosing scope, the compiler reverts to its declared type inside the closure — even above the reassignment in reading order:

TypeScript
1
2
3
4
5
6
7
8
9
let value: string | undefined; value = "hello"; const log = () => { console.log(value.toUpperCase()); // Error: 'value' is possibly 'undefined' }; value = undefined; log();

The compiler can't model what happens inside an embedded function in every case — it can't know when that function will actually be called, or whether the function itself is what reassigns the variable. Note that this only kicks in when the variable genuinely can be reassigned somewhere in the enclosing scope; a parameter or let that's never reassigned stays narrowed inside a closure without any extra work. The fix for the reassignable case is to copy the narrowed value into a local const before the closure, since a const can't be reassigned:

TypeScript
1
2
3
4
5
let value: string | undefined = "hello"; if (value !== undefined) { const narrowed = value; // const: always string, safe to capture const log = () => console.log(narrowed.toUpperCase()); }

Narrowing doesn't survive calling the same function twice. It's tempting to assume TypeScript tracks values, but it tracks expressions — and two calls to the same function are two separate expressions that could return two different things:

TypeScript
1
2
3
4
5
function run(getValue: () => string | number) { if (typeof getValue() === "string") { getValue().toUpperCase(); // Error: this is a second, independent call } }

TypeScript has no way to know getValue is pure — nothing stops it from returning a number the second time, even if it happens to be deterministic in your code. Store the result in a local variable right after the check instead of calling it again, and the narrowing holds for the rest of the block:

TypeScript
1
2
3
4
5
6
function run(getValue: () => string | number) { const value = getValue(); if (typeof value === "string") { value.toUpperCase(); // fine — one call, one narrowed variable } }

Narrowing a generic type parameter narrows the value, not the parameter. Inside a function generic over T, a typeof check on a parameter typed T doesn't make TypeScript believe T itself is string — it produces an intersection:

TypeScript
1
2
3
4
5
6
function describe<T>(value: T) { if (typeof value === "string") { // value: T & string — not string value.toUpperCase(); // fine, T & string still has toUpperCase } }

This is usually harmless: T & string still has every string method, and — because an intersection is a subtype of each of its parts — it's also still assignable back to a plain T, so returning value from inside that branch compiles fine.

The non-null assertion operator (!) is not narrowing. It's an unchecked assertion, exactly like as — it silences the error without verifying anything, and it's wrong the moment the value actually is null or undefined at runtime.

Reach for a discriminated union the moment a type has more than one optional field and the valid combinations aren't "any of the above." It turns invalid states into compile errors at the construction site instead of runtime bugs at the access site.

Write a type predicate when the same non-trivial check — more than a single typeof/instanceof/in — is repeated across a codebase, so the narrowing logic and the runtime logic can never drift apart. Keep the predicate's body honest: it is trusted completely, so an incorrect one is worse than no check at all.

Avoid as and ! wherever a narrowing check would do the same job. They're appropriate at real boundaries — parsing untyped JSON, interop with an untyped library — not as a shortcut past a union the compiler is right to flag.

Copy before you capture or re-call. If a narrowed value needs to survive a closure, or you need to use the result of a function call more than once, assign it to a local const immediately after the check. It costs one line and removes an entire category of "but I already checked this" errors.

Usually one of three reasons: the check and the use are two separate calls to the same function, which TypeScript can't assume return the same thing; the check happens outside a closure that captures a variable which can be reassigned later in the same scope; or the check is a plain boolean-returning function instead of a type predicate (x is T). See "Edge cases and gotchas" above for each fix.

No, unless its return type is explicitly a type predicate (x is T). A function declared to return plain boolean carries no information back to the call site about what became true, no matter how correct its internal logic is.

Yes — it's declared in TypeScript's standard library as isArray(arg: any): arg is any[], so if (Array.isArray(value)) narrows value to an array type inside that branch, the same as any user-defined predicate.

A type guard (x is T) returns a boolean you branch on with if/else; both branches continue. An assertion function (asserts x is T) throws when the condition is false, so there's no else — everything after the call, for the rest of that scope, is narrowed.

Narrowing checks still run, but any opts a value out of type checking entirely, so there's nothing for TypeScript to narrow from — the result of a check on an any is still any. Narrowing is only meaningful on unknown or a specific union.

TechniqueExampleNarrows to
typeoftypeof value === "string"The matching primitive type
Truthinessif (value)Removes null/undefined/other falsy members — not every falsy value of what's left
Equalityvalue === "idle" / switch (value)The matching literal member
instanceoferr instanceof TypeErrorThe matching class
in"bark" in animalThe union member that has the property
Discriminantswitch (shape.kind)The exact variant whose literal discriminant matches
User-defined guardfunction isX(v): v is XX, inside the true branch only
Assertion functionfunction assertX(v): asserts v is XX, for the rest of the scope after the call
Not narrowingas T, value!Nothing — unchecked, trusted blindly
TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// the whole pattern, copy-paste ready type Circle = { kind: "circle"; radius: number }; type Rectangle = { kind: "rectangle"; width: number; height: number }; type Shape = Circle | Rectangle; function isShape(value: unknown): value is Shape { return ( typeof value === "object" && value !== null && "kind" in value && (value.kind === "circle" || value.kind === "rectangle") ); } function area(shape: Shape): number { switch (shape.kind) { case "circle": return Math.PI * shape.radius ** 2; case "rectangle": return shape.width * shape.height; default: { const exhaustive: never = shape; // compile error if a variant is ever added and unhandled return exhaustive; } } }

Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.

  • Narrowing is control flow analysis: TypeScript tracks the most specific type each variable could have at every line, forking on every condition and merging back where branches rejoin.
  • typeof, instanceof, in, and equality checks narrow built-in and class unions directly; a plain boolean function never narrows — only a type predicate (x is T) or an assertion function (asserts x is T) does.
  • Discriminated unions turn "which optional fields are set" bugs into compile errors, and a never-typed default branch gets you exhaustiveness checking for free.
  • Narrowing is lost — not just weakened — by reassignable closures and repeated calls to the same function. Copying the narrowed value into a local const fixes both. A generic type parameter is different: narrowing still applies, it just produces an intersection (T & string) instead of collapsing T itself.

That setTimeout error from the opening isn't the compiler being difficult — it's the compiler correctly refusing to promise something it can't verify about code that runs later. Once you can see narrowing as a type environment that forks and merges line by line, every one of these errors stops being mysterious and starts being something you can predict before you even hit compile.

Which rule bit you — the closure, the repeated function call, or the generic parameter? Tell me in the comments.


🚀 Want more like this? Every guide, playground, and quiz lives on bestpractic.org — open it and sign up free so the next one finds you.

Thanks for reading! Let's stay connected:

Keep reading

One post a day, in your inbox

Each one with a runnable playground and a quiz. No pitch, no digest, unsubscribe in one click.

0 comments

Sign in to join the discussion, like comments, and save articles for later.