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.

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, theinoperator, 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.
- Why type narrowing exists
- The mental model
- Stage 1: typeof, truthiness, and equality narrowing
- Stage 2: instanceof and the in operator
- Stage 3: discriminated unions
- Stage 4: user-defined type guards and assertion functions
- Edge cases and gotchas
- Best practices
- FAQ
- Cheat sheet
- Key takeaways
Here's the naïve version of the opening story, written out in full:
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:
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:
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.
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:
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:
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:
Equality narrowing uses ===, !==, ==, and != against a specific value or another variable, and also works inside a switch:
instanceof narrows by checking the prototype chain — the standard way to distinguish classes, including the built-in Error hierarchy:
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:
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:
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 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:
Key concept:
value is stringis a promise you're making to the compiler about what atrueresult 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:
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:
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:
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 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:
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:
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.
| Technique | Example | Narrows to |
|---|---|---|
typeof | typeof value === "string" | The matching primitive type |
| Truthiness | if (value) | Removes null/undefined/other falsy members — not every falsy value of what's left |
| Equality | value === "idle" / switch (value) | The matching literal member |
instanceof | err instanceof TypeError | The matching class |
in | "bark" in animal | The union member that has the property |
| Discriminant | switch (shape.kind) | The exact variant whose literal discriminant matches |
| User-defined guard | function isX(v): v is X | X, inside the true branch only |
| Assertion function | function assertX(v): asserts v is X | X, for the rest of the scope after the call |
| Not narrowing | as T, value! | Nothing — unchecked, trusted blindly |
Think it clicked? Take the 8-question quiz →
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
constfixes both. A generic type parameter is different: narrowing still applies, it just produces an intersection (T & string) instead of collapsingTitself.
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.
- TypeScript Generics: The Complete Guide (with Cheat Sheet)
- Inferred Type Predicates Won't Save filter(Boolean). Here's What Will.
- Web Workers in JavaScript: The Complete Guide
🚀 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:
- ⭐ GitHub — follow me and star the projects: github.com/parsajiravand
- 💬 Discord — join the frontend best-practices community: discord.gg/d9KRhuAwQ
- 📸 Instagram — frontend best practices, daily: @bestpractice___
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.