Skip to content
LumenaryAcademy
Foundations 55 min

Unions and narrowing

Values that can be one of several things, and how TypeScript follows your checks to know which one you have.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

One of several things

Real values are often one thing or another. A form field holds a string, or nothing yet. A payment succeeded with a receipt, or failed with a reason. A shape is a circle, a rectangle or a triangle, each with different measurements. JavaScript handles all of these by convention: you check a field, and you remember which properties exist in each case. Forget one check, and the program reads undefined somewhere far away.

TypeScript makes the convention explicit. A union type says a value is one of several types, and the compiler tracks your checks (typeof, ===, in, instanceof, a switch on a field) to know, at every line, which of them it can be. This narrowing is the feature that makes TypeScript feel less like extra paperwork and more like a colleague reading over your shoulder. This lesson also introduces the single most useful modelling tool in the language, the discriminated union.

Worked examplesH

Unions and narrowing

Definition— union type and narrowing

A union type A | B contains every value of A and every value of B. On a value of a union type, TypeScript allows only the operations valid for every member. Narrowing is the compiler's analysis of conditions and assignments in the code, which refines a union to a smaller type inside the branches where a check has succeeded.

typescript
// A union type: a value that may be one of several types. Narrow it before using it.
type Input = string | number | boolean | Date | string[] | null;

function show(value: Input): string {
  if (value === null) return "nothing";                    // equality narrowing
  if (typeof value === "string") return `text "${value}"`; // typeof narrowing
  if (typeof value === "number") return `number ${value.toFixed(2)}`;
  if (typeof value === "boolean") return value ? "yes" : "no";
  if (value instanceof Date) return `date ${value.toISOString().slice(0, 10)}`;
  return `list of ${value.length}: ${value.join(", ")}`;  // only string[] is left
}

const inputs: Input[] = ["Quito", 2.5, true, new Date(Date.UTC(2026, 0, 15)), ["a", "b"], null];
for (const v of inputs) console.log(show(v));

// The "in" operator narrows by checking for a property.
type Cat = { meow(): string };
type Dog = { bark(): string };
function speak(pet: Cat | Dog): string {
  return "meow" in pet ? pet.meow() : pet.bark();
}
console.log(speak({ meow: () => "miau" }), speak({ bark: () => "guau" }));

// Truthiness narrowing, and narrowing by assignment.
function initials(name: string | undefined): string {
  if (!name) return "?";                                   // removes undefined (and "")
  return name.split(" ").map((part) => part[0]).join("");
}
let maybe: string | number = "start";
maybe = 42;                                                // now known to be a number
console.log(initials("Ana María Pérez"), initials(undefined), maybe.toFixed(1));

export {};
text
text "Quito"
number 2.50
yes
date 2026-01-15
list of 2: a, b
nothing
miau guau
AMP ? 42.0

Follow show line by line, as the compiler does. Each return removes a possibility, so the type of value shrinks as you go down: after the null check it is string | number | boolean | Date | string[], and by the last line only string[] is left, which is why value.length and value.join are allowed there without any check. This control-flow analysis understands if, return, throw, switch, loops, &&, || and the conditional operator.

The checks that narrow:

CheckNarrows byExample
typeof x === "string"primitive typestring, number, bigint, boolean, symbol, undefined, function, object
x === null, x !== undefined, x === "circle"equality with a valueremoves or selects literal members
if (x)truthinessremoves null and undefined (and, careful, "" and 0 at run time)
"meow" in petpresence of a propertyselects members that have it
x instanceof Dateclassselects class instances
Array.isArray(x)built-in predicateselects array members
x = 42assignmentthe variable has the assigned type until the next assignment

Without narrowing, the compiler explains exactly why an operation is not allowed:

typescript
function shout(value: string | number): string {
  return value.toUpperCase();
}
text
main.ts(2,16): error TS2339: Property 'toUpperCase' does not exist on type 'string | number'.
  Property 'toUpperCase' does not exist on type 'number'.

Two cautions. typeof null is "object" in JavaScript, and TypeScript knows it: typeof x === "object" does not remove null, which is why lesson two's describe also checked value !== null. And truthiness checks remove "", 0 and NaN along with null and undefined, so if (!name) treats an empty name as missing. Usually that is what you want for a name; it is rarely what you want for a quantity, where 0 is a real value. For numbers, test !== undefined explicitly.

Unions are sets in the sense of Lumenary Math's sets: A | B is the union of two sets of values, and an intersection A & B from the last lesson is their intersection. A narrowing check splits the set in two.

DefinitionsH

Discriminated unions

Definition— discriminated union

A discriminated union (also called a tagged union) is a union of object types that share one property, the discriminant, whose type is a different literal in each member. Checking the discriminant narrows the whole object to the matching member.

typescript
// A discriminated union: each member has a literal "kind" that identifies it.
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rectangle"; width: number; height: number }
  | { kind: "triangle"; base: number; height: number };

function assertNever(x: never): never {
  throw new Error(`unexpected value: ${JSON.stringify(x)}`);
}

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;           // shape is the circle member here
    case "rectangle":
      return shape.width * shape.height;
    case "triangle":
      return (shape.base * shape.height) / 2;
    default:
      return assertNever(shape);                    // compile error if a case is missing
  }
}

const shapes: Shape[] = [
  { kind: "circle", radius: 1 },
  { kind: "rectangle", width: 3, height: 4 },
  { kind: "triangle", base: 6, height: 2 },
];
for (const s of shapes) console.log(s.kind.padEnd(10), area(s).toFixed(3));

const total = shapes.reduce((sum, s) => sum + area(s), 0);
console.log("total", total.toFixed(3));

export {};
text
circle     3.142
rectangle  12.000
triangle   6.000
total 21.142

Inside case "circle":, TypeScript knows shape is the circle member, so shape.radius is allowed; outside, it is not, because rectangles have no radius. The default branch is the clever part. If every case is handled, nothing can reach it, and shape has been narrowed to never, the empty type, so calling assertNever(shape) type-checks. Now suppose a colleague adds the triangle to Shape but forgets area. Delete the two triangle lines from area in the program above, and the compiler says:

text
main.ts(18,26): error TS2345: Argument of type '{ kind: "triangle"; base: number; height: number; }' is not assignable to parameter of type 'never'.

The unhandled member appears by name, at the exact line. This is exhaustiveness checking, and it turns "add a new kind of thing" from a search through the code base into a list of compiler errors to fix. The assertNever function also protects you at run time, if data that the types didn't anticipate arrives anyway.

Discriminated unions are how TypeScript programs model anything with variants: messages in a protocol, actions in a state store (Redux's actions are the classic example), nodes in a syntax tree, the events of lesson nine of the JavaScript course. The discriminant is conventionally called kind, type or status. Languages such as Rust, Haskell and OCaml build the same idea into their core as algebraic data types; TypeScript gets it from ordinary objects and literal types.

ComputationC

Modelling states and failures

A common bug in user interfaces comes from describing a loading screen with separate flags: isLoading, hasError, data. Nothing stops isLoading and hasError both being true, or data being set while an old error is still shown. A union of states makes impossible combinations impossible to write:

typescript
// Modelling states with a union instead of several booleans.
type RemoteData<T> =
  | { status: "idle" }
  | { status: "loading"; startedAt: number }
  | { status: "success"; data: T }
  | { status: "error"; error: string; retryable: boolean };

interface Forecast {
  city: string;
  highC: number;
}

function render(state: RemoteData<Forecast[]>): string {
  switch (state.status) {
    case "idle":
      return "Choose a city to see its forecast.";
    case "loading":
      return `Loading... (started at t=${state.startedAt})`;
    case "success":
      return state.data.map((f) => `${f.city}: ${f.highC} °C`).join("; ");
    case "error":
      return `Could not load forecasts: ${state.error}${state.retryable ? " (try again)" : ""}`;
  }
}

const states: RemoteData<Forecast[]>[] = [
  { status: "idle" },
  { status: "loading", startedAt: 1200 },
  { status: "success", data: [{ city: "Hanoi", highC: 29 }, { city: "Oslo", highC: 4 }] },
  { status: "error", error: "HTTP 503", retryable: true },
];
for (const s of states) console.log(render(s));

// A Result type: success or failure, and the caller must look before using the value.
type Result<T, E = string> = { ok: true; value: T } | { ok: false; error: E };

function parsePercent(text: string): Result<number> {
  const n = Number(text.replace("%", ""));
  if (text.trim() === "" || Number.isNaN(n)) return { ok: false, error: `not a number: "${text}"` };
  if (n < 0 || n > 100) return { ok: false, error: `out of range: ${n}` };
  return { ok: true, value: n / 100 };
}

for (const text of ["45%", "120", "abc"]) {
  const r = parsePercent(text);
  console.log(r.ok ? `ok ${r.value}` : `error ${r.error}`);
}

export {};
text
Choose a city to see its forecast.
Loading... (started at t=1200)
Hanoi: 29 °C; Oslo: 4 °C
Could not load forecasts: HTTP 503 (try again)
ok 0.45
error out of range: 120
error not a number: "abc"

Each state carries exactly the data that makes sense in it: there is no data while loading, and no error message after success. render has no default and no assertNever, yet it is still checked for exhaustiveness, in a different way: its declared return type is string, so if a state is left unhandled, the function could fall off the end and return undefined. Add a fifth member, | { status: "cancelled" }, to RemoteData without handling it, and the compiler points at render's return type:

text
main.ts(14,49): error TS2366: Function lacks ending return statement and return type does not include 'undefined'.

(The <T> in RemoteData<T> makes the type generic, so the same states work for any kind of data; lesson six covers generics.)

The second half shows a Result type, a union with a boolean discriminant ok. It is the "return, don't throw" style from the JavaScript course's lesson on errors, now enforced by the compiler: a caller cannot read r.value without first checking r.ok, so forgetting to handle failure is a compile error rather than a production incident. Result types suit failures that are expected and routine, such as parsing user input; exceptions remain the right tool for the unexpected. Code bases that use them heavily usually add a few small helpers, such as one that turns a Result into its value or throws, for the places where a failure really would be a bug, and one that applies a function to the value only when ok is true.

Worked examplesH

Type predicates and assertion functions

Sometimes the check that tells two types apart is more than a single typeof, and you want to give it a name. A type predicate is a return type of the form x is T, on a function that returns a boolean; when it returns true, the argument is narrowed to T.

typescript
// Type predicates: your own functions that narrow.
interface Book { title: string; isbn: string }
interface Film { title: string; minutes: number }
type Item = Book | Film;

function isBook(item: Item): item is Book {
  return "isbn" in item;
}

const shelf: Item[] = [
  { title: "Half of a Yellow Sun", isbn: "978-0007200283" },
  { title: "Spirited Away", minutes: 125 },
  { title: "Pedro Páramo", isbn: "978-0802133908" },
];

const books = shelf.filter(isBook);                 // Book[], thanks to the predicate
console.log(books.map((b) => b.isbn).join(", "));

// Since TypeScript 5.5, simple predicates are inferred: titles is string[], not (string | undefined)[].
const titles = ["Dune", undefined, "Kindred"].filter((t) => t !== undefined);
console.log(titles.map((t) => t.toUpperCase()));

// Assertion functions: throw if the condition fails, and narrow if it returns.
function assertIsString(value: unknown, name: string): asserts value is string {
  if (typeof value !== "string") throw new TypeError(`${name} must be a string`);
}
const fromForm: unknown = "  Ifeoma ";
assertIsString(fromForm, "name");
console.log(`[${fromForm.trim()}]`);               // fromForm is a string from here on

// catch variables are unknown: narrow with instanceof before using them.
try {
  JSON.parse("{oops}");
} catch (err) {
  const message = err instanceof Error ? `${err.name}: ${err.message}` : String(err);
  console.log(message);
}

export {};
text
978-0007200283, 978-0802133908
[ 'DUNE', 'KINDRED' ]
[Ifeoma]
SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
  • isBook is a predicate, and passing it to filter narrows the result: books is Book[], so b.isbn is allowed.
  • Since TypeScript 5.5, the compiler infers a predicate for simple arrow functions like (t) => t !== undefined, so titles is string[]. Before 5.5, it remained (string | undefined)[], and code was full of explicit (t): t is string => annotations.
  • An assertion function has the return type asserts value is T: it returns normally only if the condition holds, and throws otherwise, so after the call the compiler treats value as narrowed. It suits checks at the start of a function, where failure should stop everything.
  • The catch variable is unknown under --strict, because JavaScript can throw anything. err instanceof Error narrows it safely.

A predicate is a promise that the compiler does not check. function isBook(x: unknown): x is Book { return true; } compiles without complaint, and then every non-book that passes through it is typed as a book. Keep predicates small, obviously correct and tested, because the rest of the program will trust them completely.

ExplanationH

Designing with unions

Once unions and narrowing are second nature, they change how you design functions and data. Some habits experienced TypeScript developers share:

Literal unions instead of booleans. A call like sortBy("price", true) says nothing about what true means. sortBy("price", "descending"), with a parameter of type "ascending" | "descending", reads aloud correctly, and a third option can be added later without changing every caller's meaning.

Exhaustive lookup tables. A Record keyed by a union must have a key for every member, so a table of labels or icons is checked just like a switch:

typescript
type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "rectangle"; width: number; height: number }
  | { kind: "triangle"; base: number; height: number };

const labels: Record<Shape["kind"], string> = {
  circle: "Circle",
  rectangle: "Rectangle",
};
text
main.ts(6,7): error TS2741: Property 'triangle' is missing in type '{ circle: string; rectangle: string; }' but required in type 'Record<"circle" | "rectangle" | "triangle", string>'.

Shape["kind"], an indexed access type from lesson three, collects the discriminants of every member into "circle" | "rectangle" | "triangle", so the table follows the union automatically.

Say what "nothing" means. T | undefined is the natural "maybe" in TypeScript, matching what JavaScript gives for missing properties and failed lookups. Many teams reserve null for values that come from JSON or a database, where it is the convention, and use undefined everywhere else. Whichever you choose, distinguish "not found" (a normal result, perhaps undefined) from "something went wrong" (an exception, or the error arm of a Result); collapsing both into undefined hides failures.

Parse, then trust. Narrow raw input into precise types once, at the edge of the program, and pass the precise types inward. A function that accepts a Shape never needs to re-check that a circle has a radius; that was settled when the shape was created. This principle, often summarised as "parse, don't validate", is the thread that connects this lesson to the validation libraries of lesson nine.

Common misconceptionsH

Common misconceptions

Misconception

"A union A | B lets me use the properties of A or of B." Before narrowing, it allows only what both have. That is the point: the compiler won't let you assume which one you hold until you have checked.

Misconception

"Narrowing changes the value." It changes only what the compiler knows about the value, in a region of code. At run time, it is the ordinary if or switch you wrote that does the work.

Misconception

"A default case is always good practice." For a discriminated union, a default that silently returns something defeats exhaustiveness checking: a new member would fall into it unnoticed. Use assertNever in the default, or no default with a declared return type, so the compiler can tell you what you missed.

Misconception

"Narrowing always survives inside callbacks." A callback may run later, after the value has changed, so the compiler is cautious. Narrowing of a property, such as o.v !== undefined, is forgotten inside a callback created afterwards, and so is narrowing of a let variable that is assigned again later in the function. (Since TypeScript 5.4, a let that is not reassigned after the callback is created keeps its narrowing.) The reliable fix is to copy the narrowed value into a const before creating the callback; narrowing of a const is always kept.

Exercises

Exercises

For each question, follow the code as the compiler does: what is the type of each name on each line?

1. Unions and narrowing

Warm-upComputational

What does this print?

function f(x: string | number): number {
  if (typeof x === "string") return x.length;
  return x * 2;
}
console.log(f("abc"), f(4));
export {};

2. Unions and narrowing

CoreComputational

In the lesson's show function, the parameter has type string | number | boolean | Date | string[] | null. What is the type of value on the last line, after the checks for null, string, number, boolean and Date have each returned?

3. Unions and narrowing

CoreComputational

Given declare const s: string | undefined;, inside which of these if blocks is s narrowed to string? Choose all that apply.

Choose all that apply

4. Unions and narrowing

CoreComputational

Using the lesson's parsePercent, what does this print?

const results = ["7%", "-3", ""].map(parsePercent);
console.log(results.filter((r) => r.ok).length, results.map((r) => (r.ok ? r.value : r.error)).join(" | "));

5. Unions and narrowing

CoreHuman

A Shape union gains a new member, { kind: "hexagon"; side: number }. area uses a switch on shape.kind with default: return assertNever(shape); and has no hexagon case. What happens?

Choose one

6. Unions and narrowing

StretchHuman

function isBook(x: unknown): x is Book { return true; } compiles. What does that tell you about type predicates?

Choose one

7. Unions and narrowing

CoreHuman

A component's state is { isLoading: boolean; error?: string; data?: Forecast[] }. What is the main advantage of replacing it with a discriminated union of idle, loading, success and error states?

Choose one

Further reading and resources