[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"verticals":3,"quiz-weekly-typescript-type-narrowing":44,"search-suggestions":60,"quiz-article-weekly-typescript-type-narrowing":109,"path-membership-weekly-typescript-type-narrowing":591},[4,20,32],{"id":5,"slug":6,"name":7,"tagline":8,"description":9,"accentFrom":10,"accentTo":11,"icon":12,"defaultLocale":13,"locales":14,"features":16,"position":19},"019fe637-3d33-714b-b57f-23e163ffca0c","dev","Web Development","Read it. Run it. Prove it.","A post a day on modern web development — most with an editable playground and a quiz that explains every answer. Free, no account needed.","violet-500","cyan-400","◇","en",[13,15],"fa",{"courses":17,"paths":17,"articles":17,"exams":18,"flashcards":18,"packages":17,"community":17,"certificates":17,"teams":17,"commerce":17},true,false,0,{"id":21,"slug":22,"name":23,"tagline":24,"description":25,"accentFrom":26,"accentTo":10,"icon":27,"defaultLocale":13,"locales":28,"features":30,"position":31},"019fe637-3dc2-754c-8657-0f175bfee7c6","lang","Languages","Learn a language the way you learn a codebase.","Grammar explained the way good documentation explains an API — one idea at a time, each with a quiz.","amber-400","⌘",[13,15,29],"es",{"courses":18,"paths":18,"articles":17,"exams":18,"flashcards":17,"packages":18,"community":17,"certificates":17,"teams":18,"commerce":18},2,{"id":33,"slug":34,"name":35,"tagline":36,"description":37,"accentFrom":38,"accentTo":39,"icon":40,"defaultLocale":13,"locales":41,"features":42,"position":43},"7b3c16f2-931d-410e-802e-e1fa4edab7de","soft","Soft Skills","The half of the job nobody wrote documentation for.","Weekly, on the parts of working life that decide more than your code does — first weeks, meetings, interviews, promotions, and the people around you. Written from what actually happens, and recorded as a podcast you can listen to on the walk.","emerald-400","teal-300","◉",[13],{"courses":18,"paths":18,"articles":17,"exams":18,"flashcards":18,"packages":18,"community":17,"certificates":18,"teams":18,"commerce":18},3,{"id":45,"slug":46,"kind":47,"title":48,"description":49,"config":50,"verticalId":5,"vertical":55,"course":52,"_count":56,"access":57,"attempts":59,"questionCount":51},"01a1fce0-ca11-720b-8a46-4d982ba9047f","weekly-typescript-type-narrowing","PRACTICE_QUIZ","TypeScript Type Narrowing","Test what you just learned about control flow analysis, typeof\u002Finstanceof\u002Fin guards, discriminated unions, type predicates, and the closure and generic gotchas that trip people up.",{"questionCount":51,"timeLimitSec":52,"shuffleQuestions":18,"shuffleOptions":17,"negativeMarking":19,"passScorePct":53,"maxAttempts":52,"revealAnswers":54,"allowFlagging":18,"allowBacktracking":17},8,null,70,"AFTER_SUBMIT",{"slug":6,"name":7},{"questions":51},{"allowed":17,"reason":58},"FREE",[],[61,65,69,73,77,81,85,89,93,97,101,105],{"slug":62,"name":63,"articles":64},"webdev","Webdev",195,{"slug":66,"name":67,"articles":68},"javascript","Javascript",156,{"slug":70,"name":71,"articles":72},"frontend","Frontend",103,{"slug":74,"name":75,"articles":76},"tutorial","Tutorial",85,{"slug":78,"name":79,"articles":80},"css","Css",56,{"slug":82,"name":83,"articles":84},"typescript","Typescript",36,{"slug":86,"name":87,"articles":88},"performance","Performance",33,{"slug":90,"name":91,"articles":92},"programming","Programming",26,{"slug":94,"name":95,"articles":96},"react","React",23,{"slug":98,"name":99,"articles":100},"node","Node",19,{"slug":102,"name":103,"articles":104},"browser","Browser",18,{"slug":106,"name":107,"articles":108},"nextjs","Nextjs",13,{"id":110,"slug":46,"title":111,"subtitle":52,"excerpt":112,"coverUrl":113,"locale":13,"readingMinutes":114,"publishedAt":115,"viewCount":116,"likeCount":19,"commentCount":19,"author":117,"vertical":122,"topic":123,"tags":125,"_count":130,"playground":132,"body":134,"bodyMd":540,"seo":541,"translationGroupId":543,"series":544,"podcastUrl":52,"verticalId":5,"thread":582,"assessments":584,"translations":587,"quiz":589},"01a1fce0-c9cc-7004-b075-6c0ff7c7b600","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.","\u002Fmedia\u002Fcovers\u002Fweekly-typescript-type-narrowing.png",15,"2026-11-27T11:46:59.418Z",24,{"id":118,"name":119,"username":120,"avatarUrl":52,"headline":121},"019fe637-3c25-7088-9034-39c9f15dc3c8","Parsa Jiravand","parsa","Frontend engineer · building bestpractic",{"slug":6,"name":7,"accentFrom":10,"accentTo":11},{"slug":82,"name":124},"TypeScript",[126,127,128,129],{"slug":82,"name":83,"color":52},{"slug":66,"name":67,"color":52},{"slug":74,"name":75,"color":52},{"slug":62,"name":63,"color":52},{"assessments":131},1,{"slug":46,"title":133},"TypeScript type narrowing — interactive playground",{"blocks":135,"version":131},[136,140,145,148,157,160,163,177,180,183,189,192,195,199,202,205,209,212,215,218,222,226,229,232,236,239,243,246,250,253,257,260,263,267,270,273,277,280,283,287,290,293,296,299,302,305,308,311,315,318,322,325,328,332,335,338,342,345,349,352,356,359,363,366,370,373,376,379,382,385,388,391,394,397,400,404,407,411,414,418,421,425,428,431,475,479,482,485,488,491,494,497,504,507,510,513,516,522,525,528,531,534],{"id":137,"html":138,"type":139},"b1","\u003Cp>You write \u003Ccode>function greet(value: string | null)\u003C\u002Fcode>, guard it with \u003Ccode>if (value === null) return;\u003C\u002Fcode>, and schedule a \u003Ccode>setTimeout\u003C\u002Fcode> callback that uses \u003Ccode>value\u003C\u002Fcode>. Right after scheduling it, you reset \u003Ccode>value\u003C\u002Fcode> back to \u003Ccode>null\u003C\u002Fcode> — a one-line cleanup, nothing dramatic. TypeScript suddenly reports &quot;\u003Ccode>value\u003C\u002Fcode> is possibly \u003Ccode>null\u003C\u002Fcode>&quot; \u003Cstrong>inside the callback\u003C\u002Fstrong>, 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 \u003Cstrong>type narrowing\u003C\u002Fstrong>, the mechanism TypeScript uses to track which members of a union type are still possible at each line of your code.\u003C\u002Fp>","paragraph",{"id":141,"html":142,"text":143,"type":144,"level":31},"b2","What you&#39;ll learn","What you'll learn","heading",{"id":146,"html":147,"type":139},"b3","\u003Cp>By the end of this guide you&#39;ll be able to:\u003C\u002Fp>",{"id":149,"type":150,"items":151,"ordered":18},"b4","list",[152,153,154,155,156],"Explain what control flow analysis actually tracks as it reads your code","Use \u003Ccode>typeof\u003C\u002Fcode>, \u003Ccode>instanceof\u003C\u002Fcode>, the \u003Ccode>in\u003C\u002Fcode> operator, and equality checks to narrow a union correctly","Model variants with \u003Cstrong>discriminated unions\u003C\u002Fstrong> instead of a pile of optional fields","Write your own type guard (\u003Ccode>x is T\u003C\u002Fcode>) and assertion functions, and know when a plain boolean function won&#39;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",{"id":158,"html":159,"type":139},"b5","\u003Cp>\u003Cstrong>Who this is for:\u003C\u002Fstrong> you&#39;ve written union types and \u003Ccode>if\u003C\u002Fcode> checks in TypeScript, and you&#39;ve either hit a narrowing error that didn&#39;t make sense, or you want to know what the compiler is actually doing instead of treating it as a black box.\u003C\u002Fp>",{"id":161,"html":162,"text":162,"type":144,"level":31},"b6","Contents",{"id":164,"type":150,"items":165,"ordered":18},"b7",[166,167,168,169,170,171,172,173,174,175,176],"\u003Ca href=\"#why-type-narrowing-exists\">Why type narrowing exists\u003C\u002Fa>","\u003Ca href=\"#the-mental-model-a-type-environment-that-forks-and-merges\">The mental model\u003C\u002Fa>","\u003Ca href=\"#stage-1-typeof-truthiness-and-equality-narrowing\">Stage 1: typeof, truthiness, and equality narrowing\u003C\u002Fa>","\u003Ca href=\"#stage-2-instanceof-and-the-in-operator\">Stage 2: instanceof and the in operator\u003C\u002Fa>","\u003Ca href=\"#stage-3-discriminated-unions\">Stage 3: discriminated unions\u003C\u002Fa>","\u003Ca href=\"#stage-4-user-defined-type-guards-and-assertion-functions\">Stage 4: user-defined type guards and assertion functions\u003C\u002Fa>","\u003Ca href=\"#edge-cases-and-gotchas\">Edge cases and gotchas\u003C\u002Fa>","\u003Ca href=\"#best-practices\">Best practices\u003C\u002Fa>","\u003Ca href=\"#faq\">FAQ\u003C\u002Fa>","\u003Ca href=\"#cheat-sheet\">Cheat sheet\u003C\u002Fa>","\u003Ca href=\"#key-takeaways\">Key takeaways\u003C\u002Fa>",{"id":178,"html":179,"text":179,"type":144,"level":31},"b8","Why type narrowing exists",{"id":181,"html":182,"type":139},"b9","\u003Cp>Here&#39;s the naïve version of the opening story, written out in full:\u003C\u002Fp>",{"id":184,"code":185,"type":186,"language":187,"highlight":188},"b10","function shout(value: string | number | null) {\n  return value.toUpperCase(); \u002F\u002F Error: 'value' is possibly 'null'.\n  \u002F\u002F Error: Property 'toUpperCase' does not exist on type 'number'.\n}","code","ts",[],{"id":190,"html":191,"type":139},"b11","\u003Cp>\u003Ccode>value\u003C\u002Fcode>&#39;s declared type is \u003Ccode>string | number | null\u003C\u002Fcode> — 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 \u003Cstrong>every\u003C\u002Fstrong> member of the union. \u003Ccode>toUpperCase\u003C\u002Fcode> exists on \u003Ccode>string\u003C\u002Fcode>, not on \u003Ccode>number\u003C\u002Fcode> or \u003Ccode>null\u003C\u002Fcode>, so the call is rejected no matter which branch is &quot;probably&quot; true at runtime.\u003C\u002Fp>",{"id":193,"html":194,"type":139},"b12","\u003Cp>The tempting fix is to make the compiler stop complaining:\u003C\u002Fp>",{"id":196,"code":197,"type":186,"language":187,"highlight":198},"b13","function shout(value: string | number | null) {\n  return (value as string).toUpperCase(); \u002F\u002F compiles — and crashes if value is null\n}",[],{"id":200,"html":201,"type":139},"b14","\u003Cp>\u003Ccode>as string\u003C\u002Fcode> doesn&#39;t check anything — it tells TypeScript to trust you, and TypeScript does, even when you&#39;re wrong. This is the thing to avoid for this entire guide: a cast silences the error without resolving the uncertainty it was reporting.\u003C\u002Fp>",{"id":203,"html":204,"type":139},"b15","\u003Cp>The real fix is to \u003Cstrong>narrow\u003C\u002Fstrong> the union — write a check whose outcome TypeScript can use to rule members out:\u003C\u002Fp>",{"id":206,"code":207,"type":186,"language":187,"highlight":208},"b16","function shout(value: string | number | null) {\n  if (typeof value !== \"string\") return;\n  return value.toUpperCase(); \u002F\u002F value: string here — no cast needed\n}",[],{"id":210,"html":211,"type":139},"b17","\u003Cp>Nothing about \u003Ccode>value\u003C\u002Fcode>&#39;s declared type changed. What changed is TypeScript&#39;s \u003Cem>belief\u003C\u002Fem> about which members of that union are still possible at this specific line, given the \u003Ccode>typeof\u003C\u002Fcode> check that just ran and returned early.\u003C\u002Fp>",{"id":213,"html":214,"text":214,"type":144,"level":31},"b18","The mental model: a type environment that forks and merges",{"id":216,"html":217,"type":139},"b19","\u003Cp>\u003Cstrong>The mental model:\u003C\u002Fstrong> as TypeScript reads your function from top to bottom, it maintains a type for every variable at \u003Cem>that exact point in the code\u003C\u002Fem> — not one fixed type for the whole function. This per-line tracking is called \u003Cstrong>control flow analysis\u003C\u002Fstrong>. Every \u003Ccode>if\u003C\u002Fcode>, \u003Ccode>else\u003C\u002Fcode>, \u003Ccode>return\u003C\u002Fcode>, \u003Ccode>throw\u003C\u002Fcode>, \u003Ccode>&amp;&amp;\u003C\u002Fcode>, \u003Ccode>||\u003C\u002Fcode>, and \u003Ccode>switch\u003C\u002Fcode> forks that tracking into branches, and every point where branches rejoin (the line after an \u003Ccode>if\u003C\u002Fcode> block, say) merges the types back together as a union of whatever each branch produced.\u003C\u002Fp>",{"id":219,"code":220,"type":186,"language":187,"highlight":221},"b20","function example(value: string | number | null) {\n  \u002F\u002F value: string | number | null\n  if (value === null) {\n    \u002F\u002F value: null\n    return;\n  }\n  \u002F\u002F value: string | number   (the null branch returned, so it's gone)\n  if (typeof value === \"string\") {\n    \u002F\u002F value: string\n  } else {\n    \u002F\u002F value: number           (the only thing left once string is ruled out)\n  }\n  \u002F\u002F value: string | number   (merged back after the if\u002Felse)\n}",[],{"id":223,"html":224,"type":225},"b21","\u003Cp>\u003Cstrong>Key concept:\u003C\u002Fstrong> narrowing is not a special annotation you add — it&#39;s TypeScript running the same reasoning you would, mechanically, on every condition in your code, and remembering the result line by line.\u003C\u002Fp>\n","quote",{"id":227,"html":228,"text":228,"type":144,"level":31},"b22","Stage 1: typeof, truthiness, and equality narrowing",{"id":230,"html":231,"type":139},"b23","\u003Cp>\u003Cstrong>\u003Ccode>typeof\u003C\u002Fcode>\u003C\u002Fstrong> narrows unions of primitives — \u003Ccode>string\u003C\u002Fcode>, \u003Ccode>number\u003C\u002Fcode>, \u003Ccode>boolean\u003C\u002Fcode>, \u003Ccode>bigint\u003C\u002Fcode>, \u003Ccode>symbol\u003C\u002Fcode>, \u003Ccode>undefined\u003C\u002Fcode>, \u003Ccode>function\u003C\u002Fcode>, and \u003Ccode>object\u003C\u002Fcode>:\u003C\u002Fp>",{"id":233,"code":234,"type":186,"language":187,"highlight":235},"b24","function format(value: string | number) {\n  if (typeof value === \"number\") {\n    return value.toFixed(2); \u002F\u002F value: number\n  }\n  return value.trim(); \u002F\u002F value: string\n}",[],{"id":237,"html":238,"type":139},"b25","\u003Cp>\u003Cstrong>Truthiness narrowing\u003C\u002Fstrong> uses any value in boolean position — an \u003Ccode>if\u003C\u002Fcode>, a \u003Ccode>&amp;&amp;\u003C\u002Fcode>, a ternary — and rules out the falsy members of a union (\u003Ccode>null\u003C\u002Fcode>, \u003Ccode>undefined\u003C\u002Fcode>, \u003Ccode>&quot;&quot;\u003C\u002Fcode>, \u003Ccode>0\u003C\u002Fcode>, \u003Ccode>false\u003C\u002Fcode>, \u003Ccode>NaN\u003C\u002Fcode>) that the \u003Cem>type\u003C\u002Fem> can represent, not every falsy value of the remaining type:\u003C\u002Fp>",{"id":240,"code":241,"type":186,"language":187,"highlight":242},"b26","function printLength(value: string | null | undefined) {\n  if (value) {\n    console.log(value.length); \u002F\u002F value: string — null and undefined are ruled out\n  }\n}",[],{"id":244,"html":245,"type":139},"b27","\u003Cp>Watch the gap here: \u003Ccode>if (value)\u003C\u002Fcode> also excludes the empty string \u003Ccode>&quot;&quot;\u003C\u002Fcode>, which is a perfectly valid \u003Ccode>string\u003C\u002Fcode>. Truthiness narrowing removes \u003Ccode>null | undefined\u003C\u002Fcode> from the \u003Cem>type\u003C\u002Fem>, but it does not mean &quot;every string reached this branch&quot; — an empty string never gets here at runtime either. For that reason, prefer an explicit check when the empty string matters:\u003C\u002Fp>",{"id":247,"code":248,"type":186,"language":187,"highlight":249},"b28","if (value !== null && value !== undefined) {\n  console.log(value.length); \u002F\u002F value: string, including \"\"\n}",[],{"id":251,"html":252,"type":139},"b29","\u003Cp>\u003Cstrong>Equality narrowing\u003C\u002Fstrong> uses \u003Ccode>===\u003C\u002Fcode>, \u003Ccode>!==\u003C\u002Fcode>, \u003Ccode>==\u003C\u002Fcode>, and \u003Ccode>!=\u003C\u002Fcode> against a specific value or another variable, and also works inside a \u003Ccode>switch\u003C\u002Fcode>:\u003C\u002Fp>",{"id":254,"code":255,"type":186,"language":187,"highlight":256},"b30","type Status = \"idle\" | \"loading\" | \"success\" | \"error\";\n\nfunction describe(status: Status) {\n  switch (status) {\n    case \"idle\":\n      return \"Not started\"; \u002F\u002F status: \"idle\"\n    case \"error\":\n      return \"Something went wrong\"; \u002F\u002F status: \"error\"\n    default:\n      return \"In progress\"; \u002F\u002F status: \"loading\" | \"success\"\n  }\n}",[],{"id":258,"html":259,"text":259,"type":144,"level":31},"b31","Stage 2: instanceof and the in operator",{"id":261,"html":262,"type":139},"b32","\u003Cp>\u003Cstrong>\u003Ccode>instanceof\u003C\u002Fcode>\u003C\u002Fstrong> narrows by checking the prototype chain — the standard way to distinguish classes, including the built-in \u003Ccode>Error\u003C\u002Fcode> hierarchy:\u003C\u002Fp>",{"id":264,"code":265,"type":186,"language":187,"highlight":266},"b33","async function load(url: string) {\n  try {\n    return await fetch(url);\n  } catch (err) {\n    if (err instanceof TypeError) {\n      console.error(\"Network failure:\", err.message); \u002F\u002F err: TypeError\n    }\n    throw err;\n  }\n}",[],{"id":268,"html":269,"type":139},"b34","\u003Cp>This matters because a \u003Ccode>catch\u003C\u002Fcode> clause&#39;s variable is typed \u003Ccode>unknown\u003C\u002Fcode> by default in modern TypeScript (\u003Ccode>useUnknownInCatchVariables\u003C\u002Fcode>) — you&#39;re required to narrow it, with \u003Ccode>instanceof\u003C\u002Fcode> or \u003Ccode>typeof\u003C\u002Fcode>, before touching \u003Ccode>.message\u003C\u002Fcode> or anything else on it.\u003C\u002Fp>",{"id":271,"html":272,"type":139},"b35","\u003Cp>\u003Cstrong>The \u003Ccode>in\u003C\u002Fcode> operator\u003C\u002Fstrong> narrows object unions by checking whether a property exists, which is the tool to reach for when the members aren&#39;t class instances:\u003C\u002Fp>",{"id":274,"code":275,"type":186,"language":187,"highlight":276},"b36","type Dog = { bark(): void };\ntype Cat = { meow(): void };\n\nfunction speak(animal: Dog | Cat) {\n  if (\"bark\" in animal) {\n    animal.bark(); \u002F\u002F animal: Dog\n  } else {\n    animal.meow(); \u002F\u002F animal: Cat\n  }\n}",[],{"id":278,"html":279,"text":279,"type":144,"level":31},"b37","Stage 3: discriminated unions",{"id":281,"html":282,"type":139},"b38","\u003Cp>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 \u003Ccode>in\u003C\u002Fcode>\u002F\u003Ccode>typeof\u003C\u002Fcode> nothing clean to check — give every variant a shared, literal-typed property (the \u003Cstrong>discriminant\u003C\u002Fstrong>) and let the value of that one property select the whole shape:\u003C\u002Fp>",{"id":284,"code":285,"type":186,"language":187,"highlight":286},"b39","\u002F\u002F the shape that invites bugs: are width\u002Fheight and radius ever both set? neither?\ntype BadShape = {\n  kind: \"circle\" | \"rectangle\";\n  radius?: number;\n  width?: number;\n  height?: number;\n};\n\n\u002F\u002F the discriminated union: each variant is its own exact type\ntype Circle = { kind: \"circle\"; radius: number };\ntype Rectangle = { kind: \"rectangle\"; width: number; height: number };\ntype Shape = Circle | Rectangle;\n\nfunction area(shape: Shape) {\n  switch (shape.kind) {\n    case \"circle\":\n      return Math.PI * shape.radius ** 2; \u002F\u002F shape: Circle — width\u002Fheight don't exist here\n    case \"rectangle\":\n      return shape.width * shape.height; \u002F\u002F shape: Rectangle\n  }\n}",[],{"id":288,"html":289,"type":139},"b40","\u003Cp>Checking \u003Ccode>shape.kind\u003C\u002Fcode> against a specific literal narrows \u003Ccode>shape\u003C\u002Fcode> itself to the one member of the union whose \u003Ccode>kind\u003C\u002Fcode> field has that literal type — this works because every variant&#39;s discriminant is a distinct literal, not the general \u003Ccode>string\u003C\u002Fcode>. Add a \u003Ccode>default\u003C\u002Fcode> branch that returns \u003Ccode>shape satisfies never\u003C\u002Fcode> (or assigns \u003Ccode>shape\u003C\u002Fcode> to a variable typed \u003Ccode>never\u003C\u002Fcode>) and the compiler will flag any future variant you forget to handle — that&#39;s \u003Cstrong>exhaustiveness checking\u003C\u002Fstrong>, a direct payoff of narrowing a discriminated union down to nothing, worth its own guide.\u003C\u002Fp>",{"id":291,"html":292,"type":139},"b41","\u003C!-- playground:start -->",{"id":294,"html":295,"text":295,"type":144,"level":31},"b42","🎮 Try it yourself",{"id":297,"html":298,"type":139},"b43","\u003Cp>\u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweekly-typescript-type-narrowing\u002Fplayground\">▶️ Open the interactive playground →\u003C\u002Fa>\u003C\u002Fstrong>\u003C\u002Fp>",{"id":300,"html":301,"type":139},"b44","\u003Cp>\u003Cem>Runs right in your browser — poke at it and watch the concept react live.\u003C\u002Fem>\u003C\u002Fp>",{"id":303,"html":304,"type":139},"b45","\u003C!-- playground:end -->",{"id":306,"html":307,"text":307,"type":144,"level":31},"b46","Stage 4: user-defined type guards and assertion functions",{"id":309,"html":310,"type":139},"b47","\u003Cp>Sometimes the check you need isn&#39;t \u003Ccode>typeof\u003C\u002Fcode>, \u003Ccode>instanceof\u003C\u002Fcode>, or \u003Ccode>in\u003C\u002Fcode> — it&#39;s custom logic. A plain function returning \u003Ccode>boolean\u003C\u002Fcode> does \u003Cstrong>not\u003C\u002Fstrong> narrow, even if it&#39;s correct at runtime:\u003C\u002Fp>",{"id":312,"code":313,"type":186,"language":187,"highlight":314},"b48","function isString(value: unknown): boolean {\n  return typeof value === \"string\";\n}\n\nfunction example(value: string | number) {\n  if (isString(value)) {\n    value.toUpperCase(); \u002F\u002F Error: 'toUpperCase' does not exist on type 'string | number'\n  }\n}",[],{"id":316,"html":317,"type":139},"b49","\u003Cp>TypeScript doesn&#39;t inline the function to see what it checks — it only looks at the declared return type, and \u003Ccode>boolean\u003C\u002Fcode> carries no information about \u003Ccode>value\u003C\u002Fcode>. The fix is a \u003Cstrong>type predicate\u003C\u002Fstrong>, written as \u003Ccode>parameterName is Type\u003C\u002Fcode> in the return position:\u003C\u002Fp>",{"id":319,"code":320,"type":186,"language":187,"highlight":321},"b50","function isString(value: unknown): value is string {\n  return typeof value === \"string\";\n}\n\nfunction example(value: string | number) {\n  if (isString(value)) {\n    value.toUpperCase(); \u002F\u002F value: string — the predicate narrows it\n  }\n}",[],{"id":323,"html":324,"type":225},"b51","\u003Cp>\u003Cstrong>Key concept:\u003C\u002Fstrong> \u003Ccode>value is string\u003C\u002Fcode> is a promise you&#39;re making to the compiler about what a \u003Ccode>true\u003C\u002Fcode> 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.\u003C\u002Fp>\n",{"id":326,"html":327,"type":139},"b52","\u003Cp>\u003Cstrong>Assertion functions\u003C\u002Fstrong> (TypeScript 3.7+) are the \u003Ccode>assert\u003C\u002Fcode>-style sibling: instead of returning a boolean to branch on, they throw when the condition fails, and everything \u003Cem>after\u003C\u002Fem> the call is narrowed for the rest of the scope:\u003C\u002Fp>",{"id":329,"code":330,"type":186,"language":187,"highlight":331},"b53","function assertIsString(value: unknown): asserts value is string {\n  if (typeof value !== \"string\") {\n    throw new Error(\"Expected a string\");\n  }\n}\n\nfunction example(value: string | number) {\n  assertIsString(value);\n  value.toUpperCase(); \u002F\u002F value: string — narrowed for the rest of this scope, no if needed\n}",[],{"id":333,"html":334,"text":334,"type":144,"level":31},"b54","Edge cases and gotchas",{"id":336,"html":337,"type":139},"b55","\u003Cp>\u003Cstrong>Narrowing is lost inside a closure if the variable can be reassigned.\u003C\u002Fstrong> TypeScript can&#39;t know when a nested function will actually run, so if the outer variable is reassigned \u003Cem>anywhere\u003C\u002Fem> in the enclosing scope, the compiler reverts to its declared type inside the closure — even above the reassignment in reading order:\u003C\u002Fp>",{"id":339,"code":340,"type":186,"language":187,"highlight":341},"b56","let value: string | undefined;\nvalue = \"hello\";\n\nconst log = () => {\n  console.log(value.toUpperCase()); \u002F\u002F Error: 'value' is possibly 'undefined'\n};\n\nvalue = undefined;\nlog();",[],{"id":343,"html":344,"type":139},"b57","\u003Cp>The compiler can&#39;t model what happens inside an embedded function in every case — it can&#39;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 \u003Cem>can\u003C\u002Fem> be reassigned somewhere in the enclosing scope; a parameter or \u003Ccode>let\u003C\u002Fcode> that&#39;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 \u003Ccode>const\u003C\u002Fcode> before the closure, since a \u003Ccode>const\u003C\u002Fcode> can&#39;t be reassigned:\u003C\u002Fp>",{"id":346,"code":347,"type":186,"language":187,"highlight":348},"b58","let value: string | undefined = \"hello\";\nif (value !== undefined) {\n  const narrowed = value; \u002F\u002F const: always string, safe to capture\n  const log = () => console.log(narrowed.toUpperCase());\n}",[],{"id":350,"html":351,"type":139},"b59","\u003Cp>\u003Cstrong>Narrowing doesn&#39;t survive calling the same function twice.\u003C\u002Fstrong> It&#39;s tempting to assume TypeScript tracks \u003Cem>values\u003C\u002Fem>, but it tracks \u003Cem>expressions\u003C\u002Fem> — and two calls to the same function are two separate expressions that could return two different things:\u003C\u002Fp>",{"id":353,"code":354,"type":186,"language":187,"highlight":355},"b60","function run(getValue: () => string | number) {\n  if (typeof getValue() === \"string\") {\n    getValue().toUpperCase(); \u002F\u002F Error: this is a second, independent call\n  }\n}",[],{"id":357,"html":358,"type":139},"b61","\u003Cp>TypeScript has no way to know \u003Ccode>getValue\u003C\u002Fcode> is pure — nothing stops it from returning a \u003Ccode>number\u003C\u002Fcode> 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:\u003C\u002Fp>",{"id":360,"code":361,"type":186,"language":187,"highlight":362},"b62","function run(getValue: () => string | number) {\n  const value = getValue();\n  if (typeof value === \"string\") {\n    value.toUpperCase(); \u002F\u002F fine — one call, one narrowed variable\n  }\n}",[],{"id":364,"html":365,"type":139},"b63","\u003Cp>\u003Cstrong>Narrowing a generic type parameter narrows the value, not the parameter.\u003C\u002Fstrong> Inside a function generic over \u003Ccode>T\u003C\u002Fcode>, a \u003Ccode>typeof\u003C\u002Fcode> check on a parameter typed \u003Ccode>T\u003C\u002Fcode> doesn&#39;t make TypeScript believe \u003Ccode>T\u003C\u002Fcode> itself is \u003Ccode>string\u003C\u002Fcode> — it produces an intersection:\u003C\u002Fp>",{"id":367,"code":368,"type":186,"language":187,"highlight":369},"b64","function describe\u003CT>(value: T) {\n  if (typeof value === \"string\") {\n    \u002F\u002F value: T & string — not string\n    value.toUpperCase(); \u002F\u002F fine, T & string still has toUpperCase\n  }\n}",[],{"id":371,"html":372,"type":139},"b65","\u003Cp>This is usually harmless: \u003Ccode>T &amp; string\u003C\u002Fcode> still has every \u003Ccode>string\u003C\u002Fcode> method, and — because an intersection is a subtype of each of its parts — it&#39;s also still assignable back to a plain \u003Ccode>T\u003C\u002Fcode>, so returning \u003Ccode>value\u003C\u002Fcode> from inside that branch compiles fine.\u003C\u002Fp>",{"id":374,"html":375,"type":139},"b66","\u003Cp>\u003Cstrong>The non-null assertion operator (\u003Ccode>!\u003C\u002Fcode>) is not narrowing.\u003C\u002Fstrong> It&#39;s an unchecked assertion, exactly like \u003Ccode>as\u003C\u002Fcode> — it silences the error without verifying anything, and it&#39;s wrong the moment the value actually is \u003Ccode>null\u003C\u002Fcode> or \u003Ccode>undefined\u003C\u002Fcode> at runtime.\u003C\u002Fp>",{"id":377,"html":378,"text":378,"type":144,"level":31},"b67","Best practices",{"id":380,"html":381,"type":139},"b68","\u003Cp>\u003Cstrong>Reach for a discriminated union\u003C\u002Fstrong> the moment a type has more than one optional field and the valid combinations aren&#39;t &quot;any of the above.&quot; It turns invalid states into compile errors at the construction site instead of runtime bugs at the access site.\u003C\u002Fp>",{"id":383,"html":384,"type":139},"b69","\u003Cp>\u003Cstrong>Write a type predicate\u003C\u002Fstrong> when the same non-trivial check — more than a single \u003Ccode>typeof\u003C\u002Fcode>\u002F\u003Ccode>instanceof\u003C\u002Fcode>\u002F\u003Ccode>in\u003C\u002Fcode> — is repeated across a codebase, so the narrowing logic and the runtime logic can never drift apart. Keep the predicate&#39;s body honest: it is trusted completely, so an incorrect one is worse than no check at all.\u003C\u002Fp>",{"id":386,"html":387,"type":139},"b70","\u003Cp>\u003Cstrong>Avoid \u003Ccode>as\u003C\u002Fcode> and \u003Ccode>!\u003C\u002Fcode>\u003C\u002Fstrong> wherever a narrowing check would do the same job. They&#39;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.\u003C\u002Fp>",{"id":389,"html":390,"type":139},"b71","\u003Cp>\u003Cstrong>Copy before you capture or re-call.\u003C\u002Fstrong> 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 \u003Ccode>const\u003C\u002Fcode> immediately after the check. It costs one line and removes an entire category of &quot;but I already checked this&quot; errors.\u003C\u002Fp>",{"id":392,"html":393,"text":393,"type":144,"level":31},"b72","FAQ",{"id":395,"html":396,"text":396,"type":144,"level":43},"b73","Why does TypeScript say a value is still possibly null after I checked it?",{"id":398,"html":399,"type":139},"b74","\u003Cp>Usually one of three reasons: the check and the use are two separate calls to the same function, which TypeScript can&#39;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 (\u003Ccode>x is T\u003C\u002Fcode>). See &quot;Edge cases and gotchas&quot; above for each fix.\u003C\u002Fp>",{"id":401,"html":402,"text":403,"type":144,"level":43},"b75","Does a \u003Ccode>Boolean()\u003C\u002Fcode> or custom \u003Ccode>isTruthy()\u003C\u002Fcode> function narrow like \u003Ccode>typeof\u003C\u002Fcode> does?","Does a Boolean() or custom isTruthy() function narrow like typeof does?",{"id":405,"html":406,"type":139},"b76","\u003Cp>No, unless its return type is explicitly a type predicate (\u003Ccode>x is T\u003C\u002Fcode>). A function declared to return plain \u003Ccode>boolean\u003C\u002Fcode> carries no information back to the call site about what became true, no matter how correct its internal logic is.\u003C\u002Fp>",{"id":408,"html":409,"text":410,"type":144,"level":43},"b77","Is \u003Ccode>Array.isArray()\u003C\u002Fcode> a type guard?","Is Array.isArray() a type guard?",{"id":412,"html":413,"type":139},"b78","\u003Cp>Yes — it&#39;s declared in TypeScript&#39;s standard library as \u003Ccode>isArray(arg: any): arg is any[]\u003C\u002Fcode>, so \u003Ccode>if (Array.isArray(value))\u003C\u002Fcode> narrows \u003Ccode>value\u003C\u002Fcode> to an array type inside that branch, the same as any user-defined predicate.\u003C\u002Fp>",{"id":415,"html":416,"text":417,"type":144,"level":43},"b79","What&#39;s the difference between a type guard and an assertion function?","What's the difference between a type guard and an assertion function?",{"id":419,"html":420,"type":139},"b80","\u003Cp>A type guard (\u003Ccode>x is T\u003C\u002Fcode>) returns a boolean you branch on with \u003Ccode>if\u003C\u002Fcode>\u002F\u003Ccode>else\u003C\u002Fcode>; both branches continue. An assertion function (\u003Ccode>asserts x is T\u003C\u002Fcode>) throws when the condition is false, so there&#39;s no \u003Ccode>else\u003C\u002Fcode> — everything after the call, for the rest of that scope, is narrowed.\u003C\u002Fp>",{"id":422,"html":423,"text":424,"type":144,"level":43},"b81","Can I narrow a value typed \u003Ccode>any\u003C\u002Fcode>?","Can I narrow a value typed any?",{"id":426,"html":427,"type":139},"b82","\u003Cp>Narrowing checks still run, but \u003Ccode>any\u003C\u002Fcode> opts a value out of type checking entirely, so there&#39;s nothing for TypeScript to narrow \u003Cem>from\u003C\u002Fem> — the result of a check on an \u003Ccode>any\u003C\u002Fcode> is still \u003Ccode>any\u003C\u002Fcode>. Narrowing is only meaningful on \u003Ccode>unknown\u003C\u002Fcode> or a specific union.\u003C\u002Fp>",{"id":429,"html":430,"text":430,"type":144,"level":31},"b83","Cheat sheet",{"id":432,"head":433,"rows":437,"type":474},"b84",[434,435,436],"Technique","Example","Narrows to",[438,442,446,450,454,458,462,466,470],[439,440,441],"\u003Ccode>typeof\u003C\u002Fcode>","\u003Ccode>typeof value === &quot;string&quot;\u003C\u002Fcode>","The matching primitive type",[443,444,445],"Truthiness","\u003Ccode>if (value)\u003C\u002Fcode>","Removes \u003Ccode>null\u003C\u002Fcode>\u002F\u003Ccode>undefined\u003C\u002Fcode>\u002Fother falsy members — not every falsy value of what&#39;s left",[447,448,449],"Equality","\u003Ccode>value === &quot;idle&quot;\u003C\u002Fcode> \u002F \u003Ccode>switch (value)\u003C\u002Fcode>","The matching literal member",[451,452,453],"\u003Ccode>instanceof\u003C\u002Fcode>","\u003Ccode>err instanceof TypeError\u003C\u002Fcode>","The matching class",[455,456,457],"\u003Ccode>in\u003C\u002Fcode>","\u003Ccode>&quot;bark&quot; in animal\u003C\u002Fcode>","The union member that has the property",[459,460,461],"Discriminant","\u003Ccode>switch (shape.kind)\u003C\u002Fcode>","The exact variant whose literal discriminant matches",[463,464,465],"User-defined guard","\u003Ccode>function isX(v): v is X\u003C\u002Fcode>","\u003Ccode>X\u003C\u002Fcode>, inside the \u003Ccode>true\u003C\u002Fcode> branch only",[467,468,469],"Assertion function","\u003Ccode>function assertX(v): asserts v is X\u003C\u002Fcode>","\u003Ccode>X\u003C\u002Fcode>, for the rest of the scope after the call",[471,472,473],"Not narrowing","\u003Ccode>as T\u003C\u002Fcode>, \u003Ccode>value!\u003C\u002Fcode>","Nothing — unchecked, trusted blindly","table",{"id":476,"code":477,"type":186,"language":187,"highlight":478},"b85","\u002F\u002F the whole pattern, copy-paste ready\ntype Circle = { kind: \"circle\"; radius: number };\ntype Rectangle = { kind: \"rectangle\"; width: number; height: number };\ntype Shape = Circle | Rectangle;\n\nfunction isShape(value: unknown): value is Shape {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    \"kind\" in value &&\n    (value.kind === \"circle\" || value.kind === \"rectangle\")\n  );\n}\n\nfunction area(shape: Shape): number {\n  switch (shape.kind) {\n    case \"circle\":\n      return Math.PI * shape.radius ** 2;\n    case \"rectangle\":\n      return shape.width * shape.height;\n    default: {\n      const exhaustive: never = shape; \u002F\u002F compile error if a variant is ever added and unhandled\n      return exhaustive;\n    }\n  }\n}",[],{"id":480,"html":481,"type":139},"b86","\u003C!-- quiz:start -->",{"id":483,"html":484,"text":484,"type":144,"level":31},"b87","🧠 Test yourself",{"id":486,"html":487,"type":139},"b88","\u003Cp>Think it clicked? \u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweekly-typescript-type-narrowing\u002Fquiz\">Take the 8-question quiz →\u003C\u002Fa>\u003C\u002Fstrong>\u003C\u002Fp>",{"id":489,"html":490,"type":139},"b89","\u003Cp>\u003Cem>Instant feedback, a hint on every question, and an explanation for each answer — right or wrong.\u003C\u002Fem>\u003C\u002Fp>",{"id":492,"html":493,"type":139},"b90","\u003C!-- quiz:end -->",{"id":495,"html":496,"text":496,"type":144,"level":31},"b91","Key takeaways",{"id":498,"type":150,"items":499,"ordered":18},"b92",[500,501,502,503],"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.","\u003Ccode>typeof\u003C\u002Fcode>, \u003Ccode>instanceof\u003C\u002Fcode>, \u003Ccode>in\u003C\u002Fcode>, and equality checks narrow built-in and class unions directly; a plain boolean function never narrows — only a type predicate (\u003Ccode>x is T\u003C\u002Fcode>) or an assertion function (\u003Ccode>asserts x is T\u003C\u002Fcode>) does.","Discriminated unions turn &quot;which optional fields are set&quot; bugs into compile errors, and a \u003Ccode>never\u003C\u002Fcode>-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 \u003Ccode>const\u003C\u002Fcode> fixes both. A generic type parameter is different: narrowing still applies, it just produces an intersection (\u003Ccode>T &amp; string\u003C\u002Fcode>) instead of collapsing \u003Ccode>T\u003C\u002Fcode> itself.",{"id":505,"html":506,"type":139},"b93","\u003Cp>That \u003Ccode>setTimeout\u003C\u002Fcode> error from the opening isn&#39;t the compiler being difficult — it&#39;s the compiler correctly refusing to promise something it can&#39;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.\u003C\u002Fp>",{"id":508,"html":509,"type":139},"b94","\u003Cp>Which rule bit you — the closure, the repeated function call, or the generic parameter? Tell me in the comments.\u003C\u002Fp>",{"id":511,"html":512,"type":139},"b95","\u003C!-- related:start -->",{"id":514,"html":515,"text":515,"type":144,"level":31},"b96","📚 Read next",{"id":517,"type":150,"items":518,"ordered":18},"b97",[519,520,521],"\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweekly-typescript-generics\">TypeScript Generics: The Complete Guide (with Cheat Sheet)\u003C\u002Fa>","\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Finferred-type-predicates-filter-boolean\">Inferred Type Predicates Won&#39;t Save filter(Boolean). Here&#39;s What Will.\u003C\u002Fa>","\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweekly-web-workers\">Web Workers in JavaScript: The Complete Guide\u003C\u002Fa>",{"id":523,"html":524,"type":139},"b98","\u003C!-- related:end -->",{"id":526,"type":527},"b99","divider",{"id":529,"html":530,"type":139},"b100","\u003Cp>🚀 \u003Cstrong>Want more like this?\u003C\u002Fstrong> Every guide, playground, and quiz lives on \u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002F\">bestpractic.org\u003C\u002Fa>\u003C\u002Fstrong> — open it and \u003Cstrong>\u003Ca href=\"https:\u002F\u002Fbestpractic.org\u002F\">sign up free\u003C\u002Fa>\u003C\u002Fstrong> so the next one finds you.\u003C\u002Fp>",{"id":532,"html":533,"type":139},"b101","\u003Cp>\u003Cem>Thanks for reading! Let&#39;s stay connected:\u003C\u002Fem>\u003C\u002Fp>",{"id":535,"type":150,"items":536,"ordered":18},"b102",[537,538,539],"⭐ \u003Cstrong>GitHub\u003C\u002Fstrong> — follow me and star the projects: \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fparsajiravand\">github.com\u002Fparsajiravand\u003C\u002Fa>","💬 \u003Cstrong>Discord\u003C\u002Fstrong> — join the frontend best-practices community: \u003Ca href=\"https:\u002F\u002Fdiscord.gg\u002Fd9KRhuAwQ\">discord.gg\u002Fd9KRhuAwQ\u003C\u002Fa>","📸 \u003Cstrong>Instagram\u003C\u002Fstrong> — frontend best practices, daily: \u003Ca href=\"https:\u002F\u002Fwww.instagram.com\u002Fbestpractice___\u002F\">@bestpractice___\u003C\u002Fa>","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.\n\n## What you'll learn\n\nBy the end of this guide you'll be able to:\n\n- Explain what control flow analysis actually tracks as it reads your code\n- Use `typeof`, `instanceof`, the `in` operator, and equality checks to narrow a union correctly\n- Model variants with **discriminated unions** instead of a pile of optional fields\n- Write your own type guard (`x is T`) and assertion functions, and know when a plain boolean function won't narrow anything\n- 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\n\n**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.\n\n## Contents\n\n- [Why type narrowing exists](#why-type-narrowing-exists)\n- [The mental model](#the-mental-model-a-type-environment-that-forks-and-merges)\n- [Stage 1: typeof, truthiness, and equality narrowing](#stage-1-typeof-truthiness-and-equality-narrowing)\n- [Stage 2: instanceof and the in operator](#stage-2-instanceof-and-the-in-operator)\n- [Stage 3: discriminated unions](#stage-3-discriminated-unions)\n- [Stage 4: user-defined type guards and assertion functions](#stage-4-user-defined-type-guards-and-assertion-functions)\n- [Edge cases and gotchas](#edge-cases-and-gotchas)\n- [Best practices](#best-practices)\n- [FAQ](#faq)\n- [Cheat sheet](#cheat-sheet)\n- [Key takeaways](#key-takeaways)\n\n## Why type narrowing exists\n\nHere's the naïve version of the opening story, written out in full:\n\n```ts\nfunction shout(value: string | number | null) {\n  return value.toUpperCase(); \u002F\u002F Error: 'value' is possibly 'null'.\n  \u002F\u002F Error: Property 'toUpperCase' does not exist on type 'number'.\n}\n```\n\n`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.\n\nThe tempting fix is to make the compiler stop complaining:\n\n```ts\nfunction shout(value: string | number | null) {\n  return (value as string).toUpperCase(); \u002F\u002F compiles — and crashes if value is null\n}\n```\n\n`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.\n\nThe real fix is to **narrow** the union — write a check whose outcome TypeScript can use to rule members out:\n\n```ts\nfunction shout(value: string | number | null) {\n  if (typeof value !== \"string\") return;\n  return value.toUpperCase(); \u002F\u002F value: string here — no cast needed\n}\n```\n\nNothing 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.\n\n## The mental model: a type environment that forks and merges\n\n**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.\n\n```ts\nfunction example(value: string | number | null) {\n  \u002F\u002F value: string | number | null\n  if (value === null) {\n    \u002F\u002F value: null\n    return;\n  }\n  \u002F\u002F value: string | number   (the null branch returned, so it's gone)\n  if (typeof value === \"string\") {\n    \u002F\u002F value: string\n  } else {\n    \u002F\u002F value: number           (the only thing left once string is ruled out)\n  }\n  \u002F\u002F value: string | number   (merged back after the if\u002Felse)\n}\n```\n\n> **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.\n\n## Stage 1: typeof, truthiness, and equality narrowing\n\n**`typeof`** narrows unions of primitives — `string`, `number`, `boolean`, `bigint`, `symbol`, `undefined`, `function`, and `object`:\n\n```ts\nfunction format(value: string | number) {\n  if (typeof value === \"number\") {\n    return value.toFixed(2); \u002F\u002F value: number\n  }\n  return value.trim(); \u002F\u002F value: string\n}\n```\n\n**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:\n\n```ts\nfunction printLength(value: string | null | undefined) {\n  if (value) {\n    console.log(value.length); \u002F\u002F value: string — null and undefined are ruled out\n  }\n}\n```\n\nWatch 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:\n\n```ts\nif (value !== null && value !== undefined) {\n  console.log(value.length); \u002F\u002F value: string, including \"\"\n}\n```\n\n**Equality narrowing** uses `===`, `!==`, `==`, and `!=` against a specific value or another variable, and also works inside a `switch`:\n\n```ts\ntype Status = \"idle\" | \"loading\" | \"success\" | \"error\";\n\nfunction describe(status: Status) {\n  switch (status) {\n    case \"idle\":\n      return \"Not started\"; \u002F\u002F status: \"idle\"\n    case \"error\":\n      return \"Something went wrong\"; \u002F\u002F status: \"error\"\n    default:\n      return \"In progress\"; \u002F\u002F status: \"loading\" | \"success\"\n  }\n}\n```\n\n## Stage 2: instanceof and the in operator\n\n**`instanceof`** narrows by checking the prototype chain — the standard way to distinguish classes, including the built-in `Error` hierarchy:\n\n```ts\nasync function load(url: string) {\n  try {\n    return await fetch(url);\n  } catch (err) {\n    if (err instanceof TypeError) {\n      console.error(\"Network failure:\", err.message); \u002F\u002F err: TypeError\n    }\n    throw err;\n  }\n}\n```\n\nThis 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.\n\n**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:\n\n```ts\ntype Dog = { bark(): void };\ntype Cat = { meow(): void };\n\nfunction speak(animal: Dog | Cat) {\n  if (\"bark\" in animal) {\n    animal.bark(); \u002F\u002F animal: Dog\n  } else {\n    animal.meow(); \u002F\u002F animal: Cat\n  }\n}\n```\n\n## Stage 3: discriminated unions\n\nThis 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`\u002F`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:\n\n```ts\n\u002F\u002F the shape that invites bugs: are width\u002Fheight and radius ever both set? neither?\ntype BadShape = {\n  kind: \"circle\" | \"rectangle\";\n  radius?: number;\n  width?: number;\n  height?: number;\n};\n\n\u002F\u002F the discriminated union: each variant is its own exact type\ntype Circle = { kind: \"circle\"; radius: number };\ntype Rectangle = { kind: \"rectangle\"; width: number; height: number };\ntype Shape = Circle | Rectangle;\n\nfunction area(shape: Shape) {\n  switch (shape.kind) {\n    case \"circle\":\n      return Math.PI * shape.radius ** 2; \u002F\u002F shape: Circle — width\u002Fheight don't exist here\n    case \"rectangle\":\n      return shape.width * shape.height; \u002F\u002F shape: Rectangle\n  }\n}\n```\n\nChecking `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.\n\n\u003C!-- playground:start -->\n\n## 🎮 Try it yourself\n\n**[▶️ Open the interactive playground →](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweekly-typescript-type-narrowing\u002Fplayground)**\n\n_Runs right in your browser — poke at it and watch the concept react live._\n\n\u003C!-- playground:end -->\n\n## Stage 4: user-defined type guards and assertion functions\n\nSometimes 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:\n\n```ts\nfunction isString(value: unknown): boolean {\n  return typeof value === \"string\";\n}\n\nfunction example(value: string | number) {\n  if (isString(value)) {\n    value.toUpperCase(); \u002F\u002F Error: 'toUpperCase' does not exist on type 'string | number'\n  }\n}\n```\n\nTypeScript 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:\n\n```ts\nfunction isString(value: unknown): value is string {\n  return typeof value === \"string\";\n}\n\nfunction example(value: string | number) {\n  if (isString(value)) {\n    value.toUpperCase(); \u002F\u002F value: string — the predicate narrows it\n  }\n}\n```\n\n> **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.\n\n**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:\n\n```ts\nfunction assertIsString(value: unknown): asserts value is string {\n  if (typeof value !== \"string\") {\n    throw new Error(\"Expected a string\");\n  }\n}\n\nfunction example(value: string | number) {\n  assertIsString(value);\n  value.toUpperCase(); \u002F\u002F value: string — narrowed for the rest of this scope, no if needed\n}\n```\n\n## Edge cases and gotchas\n\n**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:\n\n```ts\nlet value: string | undefined;\nvalue = \"hello\";\n\nconst log = () => {\n  console.log(value.toUpperCase()); \u002F\u002F Error: 'value' is possibly 'undefined'\n};\n\nvalue = undefined;\nlog();\n```\n\nThe 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:\n\n```ts\nlet value: string | undefined = \"hello\";\nif (value !== undefined) {\n  const narrowed = value; \u002F\u002F const: always string, safe to capture\n  const log = () => console.log(narrowed.toUpperCase());\n}\n```\n\n**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:\n\n```ts\nfunction run(getValue: () => string | number) {\n  if (typeof getValue() === \"string\") {\n    getValue().toUpperCase(); \u002F\u002F Error: this is a second, independent call\n  }\n}\n```\n\nTypeScript 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:\n\n```ts\nfunction run(getValue: () => string | number) {\n  const value = getValue();\n  if (typeof value === \"string\") {\n    value.toUpperCase(); \u002F\u002F fine — one call, one narrowed variable\n  }\n}\n```\n\n**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:\n\n```ts\nfunction describe\u003CT>(value: T) {\n  if (typeof value === \"string\") {\n    \u002F\u002F value: T & string — not string\n    value.toUpperCase(); \u002F\u002F fine, T & string still has toUpperCase\n  }\n}\n```\n\nThis 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.\n\n**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.\n\n## Best practices\n\n**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.\n\n**Write a type predicate** when the same non-trivial check — more than a single `typeof`\u002F`instanceof`\u002F`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.\n\n**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.\n\n**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.\n\n## FAQ\n\n### Why does TypeScript say a value is still possibly null after I checked it?\n\nUsually 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.\n\n### Does a `Boolean()` or custom `isTruthy()` function narrow like `typeof` does?\n\nNo, 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.\n\n### Is `Array.isArray()` a type guard?\n\nYes — 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.\n\n### What's the difference between a type guard and an assertion function?\n\nA type guard (`x is T`) returns a boolean you branch on with `if`\u002F`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.\n\n### Can I narrow a value typed `any`?\n\nNarrowing 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.\n\n## Cheat sheet\n\n| Technique | Example | Narrows to |\n| --- | --- | --- |\n| `typeof` | `typeof value === \"string\"` | The matching primitive type |\n| Truthiness | `if (value)` | Removes `null`\u002F`undefined`\u002Fother falsy members — not every falsy value of what's left |\n| Equality | `value === \"idle\"` \u002F `switch (value)` | The matching literal member |\n| `instanceof` | `err instanceof TypeError` | The matching class |\n| `in` | `\"bark\" in animal` | The union member that has the property |\n| Discriminant | `switch (shape.kind)` | The exact variant whose literal discriminant matches |\n| User-defined guard | `function isX(v): v is X` | `X`, inside the `true` branch only |\n| Assertion function | `function assertX(v): asserts v is X` | `X`, for the rest of the scope after the call |\n| Not narrowing | `as T`, `value!` | Nothing — unchecked, trusted blindly |\n\n```ts\n\u002F\u002F the whole pattern, copy-paste ready\ntype Circle = { kind: \"circle\"; radius: number };\ntype Rectangle = { kind: \"rectangle\"; width: number; height: number };\ntype Shape = Circle | Rectangle;\n\nfunction isShape(value: unknown): value is Shape {\n  return (\n    typeof value === \"object\" &&\n    value !== null &&\n    \"kind\" in value &&\n    (value.kind === \"circle\" || value.kind === \"rectangle\")\n  );\n}\n\nfunction area(shape: Shape): number {\n  switch (shape.kind) {\n    case \"circle\":\n      return Math.PI * shape.radius ** 2;\n    case \"rectangle\":\n      return shape.width * shape.height;\n    default: {\n      const exhaustive: never = shape; \u002F\u002F compile error if a variant is ever added and unhandled\n      return exhaustive;\n    }\n  }\n}\n```\n\n\n\u003C!-- quiz:start -->\n\n## 🧠 Test yourself\n\nThink it clicked? **[Take the 8-question quiz →](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweekly-typescript-type-narrowing\u002Fquiz)**\n\n_Instant feedback, a hint on every question, and an explanation for each answer — right or wrong._\n\n\u003C!-- quiz:end -->\n## Key takeaways\n\n- 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.\n- `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.\n- Discriminated unions turn \"which optional fields are set\" bugs into compile errors, and a `never`-typed default branch gets you exhaustiveness checking for free.\n- 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.\n\nThat `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.\n\nWhich rule bit you — the closure, the repeated function call, or the generic parameter? Tell me in the comments.\n\n\u003C!-- related:start -->\n\n## 📚 Read next\n\n- [TypeScript Generics: The Complete Guide (with Cheat Sheet)](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweekly-typescript-generics)\n- [Inferred Type Predicates Won't Save filter(Boolean). Here's What Will.](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Finferred-type-predicates-filter-boolean)\n- [Web Workers in JavaScript: The Complete Guide](https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweekly-web-workers)\n\n\u003C!-- related:end -->\n\n---\n\n🚀 **Want more like this?** Every guide, playground, and quiz lives on **[bestpractic.org](https:\u002F\u002Fbestpractic.org\u002F)** — open it and **[sign up free](https:\u002F\u002Fbestpractic.org\u002F)** so the next one finds you.\n\n*Thanks for reading! Let's stay connected:*\n\n- ⭐ **GitHub** — follow me and star the projects: [github.com\u002Fparsajiravand](https:\u002F\u002Fgithub.com\u002Fparsajiravand)\n- 💬 **Discord** — join the frontend best-practices community: [discord.gg\u002Fd9KRhuAwQ](https:\u002F\u002Fdiscord.gg\u002Fd9KRhuAwQ)\n- 📸 **Instagram** — frontend best practices, daily: [@bestpractice___](https:\u002F\u002Fwww.instagram.com\u002Fbestpractice___\u002F)",{"title":111,"canonical":542,"description":112},"https:\u002F\u002Fbestpractic.org\u002Fblog\u002Fweekly-typescript-type-narrowing","01a1fce0-c9cd-750b-a668-6cffcf7bbaea",{"name":545,"part":546,"total":546,"items":547},"Deep Dive",9,[548,552,556,560,564,569,573,577,581],{"slug":549,"title":550,"publishedAt":551,"readingMinutes":108},"weekly-javascript-event-loop","JavaScript Event Loop Explained: The Complete Guide","2026-07-13T09:36:33.464Z",{"slug":553,"title":554,"publishedAt":555,"readingMinutes":114},"weekly-typescript-generics","TypeScript Generics: The Complete Guide (with Cheat Sheet)","2026-07-20T09:23:23.621Z",{"slug":557,"title":558,"publishedAt":559,"readingMinutes":114},"weekly-cors-explained","CORS Explained: The Complete Guide (with Cheat Sheet)","2026-08-03T09:54:26.268Z",{"slug":561,"title":562,"publishedAt":563,"readingMinutes":114},"weekly-javascript-proxy-reflect","JavaScript Proxy and Reflect: The Complete Guide","2026-08-24T07:06:37.948Z",{"slug":565,"title":566,"publishedAt":567,"readingMinutes":568},"weekly-javascript-closures","JavaScript Closures: The Complete Guide (with Cheat Sheet)","2026-08-25T08:53:48.904Z",14,{"slug":570,"title":571,"publishedAt":572,"readingMinutes":568},"weekly-debounce-and-throttle","Debounce and Throttle in JavaScript: The Complete Guide","2026-08-31T13:12:14.139Z",{"slug":574,"title":575,"publishedAt":576,"readingMinutes":108},"weekly-web-workers","Web Workers in JavaScript: The Complete Guide","2026-09-07T12:03:05.323Z",{"slug":578,"title":579,"publishedAt":580,"readingMinutes":114},"weekly-typescript-utility-types","TypeScript Utility Types: The Complete Guide","2026-11-27T11:41:53.859Z",{"slug":46,"title":111,"publishedAt":115,"readingMinutes":114},{"id":583,"locked":18},"01a1fce0-c9f7-7742-aacb-d4036482696a",[585],{"id":45,"slug":46,"title":48,"_count":586},{"questions":51},[588],{"locale":13,"slug":46},{"id":45,"slug":46,"title":48,"_count":590,"questionCount":51},{"questions":51},[]]