Skip to content

Lesson 37 of 50TypeScript

Unions and Narrowing

Model "this or that" with unions, narrow them safely, and make impossible states impossible with discriminated unions.

23 min read0/6 questions

Real values are rarely one thing. An id is a string or a number. A request is loading, done, or failed. A config value is set or missing. Unions describe those choices, and narrowing is how TypeScript follows your if statements to know which case you are in. This is the feature that makes TypeScript feel smart, and discriminated unions show up in every React codebase and every senior-level interview.

Union types

A union A | B means "a value of type A or type B". You can only use what is available on every member, until you check which one you have.

function formatId(id: string | number) {
  return id.toUpperCase();
  // Error: Property 'toUpperCase' does not exist on type 'string | number'.
  //   Property 'toUpperCase' does not exist on type 'number'.
}

The fix is to check the type. Inside the check, TypeScript narrows id to the matching member.

TypeScript
function formatId(id: string | number): string { if (typeof id === "string") { return id.toUpperCase(); // id: string here } return id.toString().padStart(6, "0"); // id: number here} console.log(formatId("ab12"));console.log(formatId(42));
Output
Press Run (⌘ Enter) to see what happens.

Narrowing step by step

TypeScript reads your control flow (if, return, switch, throw) and keeps track of what a variable can still be at each line. This is called control flow analysis.

How the type of `input` shrinks
  1. string | number | nullfunction parse(input: string | number | null)
  2. string | numberafter: if (input === null) return 0;
  3. stringinside: if (typeof input === "string") { ... }
  4. numberafter that block returns

At the top of the function, input could be any of the three.

1/4

The narrowing tools you will use:

CheckNarrowsExample
typeofPrimitivestypeof x === "string"
EqualityLiterals, null, undefinedx === null, status === "done"
TruthinessRemoves null, undefined, "", 0if (user)
inObjects by property"email" in contact
instanceofClass instanceserr instanceof TypeError
TypeScript
type Email = { email: string };type Phone = { phone: string }; function contactLine(c: Email | Phone): string { if ("email" in c) return "mailto:" + c.email; // c: Email return "tel:" + c.phone; // c: Phone} function describe(err: unknown): string { if (err instanceof Error) return err.message; // err: Error return String(err);} console.log(contactLine({ phone: "555-0100" }));console.log(describe(new RangeError("too big")));console.log(describe("plain string"));
Output
Press Run (⌘ Enter) to see what happens.
Quick check
What is wrong with narrowing this way?
function show(count: number | undefined) {
if (count) {
  return "Count: " + count;
}
return "No count";
}
Need a nudge? A hint rules out a wrong answer.

Discriminated unions

The most useful pattern in TypeScript. Give every member of a union a shared literal property, usually kind, type or status. Checking that one property narrows the whole object. This is a discriminated union (also called a tagged union).

type RequestState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: string[] }
  | { status: "error"; message: string };

Compare that with the shape many beginners write:

type RequestState = {
  isLoading: boolean;
  data?: string[];
  error?: string;
};
// Allows nonsense: isLoading true AND data AND error all at once.

The discriminated version makes impossible states impossible. You cannot have data while loading, and you cannot read message without first proving the status is "error".

TypeScript
type RequestState = | { status: "idle" } | { status: "loading" } | { status: "success"; data: string[] } | { status: "error"; message: string }; function render(state: RequestState): string { switch (state.status) { case "idle": return "Press search"; case "loading": return "Loading..."; case "success": return `Found ${state.data.length} results`; // state.data is available case "error": return "Error: " + state.message; // state.message is available }} console.log(render({ status: "loading" }));console.log(render({ status: "success", data: ["a", "b"] }));console.log(render({ status: "error", message: "timeout" }));
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

What does this print?

type Result =
| { ok: true; value: number }
| { ok: false; error: string };

function show(r: Result) {
return r.ok ? r.value * 2 : r.error.length;
}

console.log(show({ ok: true, value: 21 }), show({ ok: false, error: "nope" }));
Need a nudge? Hints walk you through it.

Exhaustiveness checking with never

What happens when someone adds a new state, say { status: "cancelled" }, and forgets to update render? You want a compile error, not a silent undefined. Assign the leftover value to never in the default branch.

function render(state: RequestState): string {
  switch (state.status) {
    case "idle": return "Press search";
    case "loading": return "Loading...";
    case "success": return `Found ${state.data.length}`;
    case "error": return "Error: " + state.message;
    default: {
      const unhandled: never = state;
      // Error (after adding "cancelled"):
      // Type '{ status: "cancelled"; }' is not assignable to type 'never'.
      throw new Error("Unhandled state");
    }
  }
}

When every case is handled, nothing is left and state has type never in default, so the assignment compiles. The moment a case is missing, the leftover member cannot be assigned to never, and the compiler points straight at the switch you forgot.

Quick check
Why does const unhandled: never = state compile when every case is handled?
Need a nudge? A hint rules out a wrong answer.

Type predicates and assertion functions

Sometimes the check is too complex for an inline if. Move it into a function and give it a type predicate return type, value is Type. When it returns true, callers get the narrowing.

TypeScript
type User = { id: number; email: string }; function isUser(value: unknown): value is User { return ( typeof value === "object" && value !== null && typeof (value as User).id === "number" && typeof (value as User).email === "string" );} const data: unknown = JSON.parse('{"id": 1, "email": "ada@example.com"}'); if (isUser(data)) { console.log(data.email); // data: User} const mixed = [1, null, 2, undefined, 3];const nums = mixed.filter((x): x is number => x != null);console.log(nums);
Output
Press Run (⌘ Enter) to see what happens.

Since TypeScript 5.5, simple callbacks like x => x != null infer the predicate automatically, so filter returns number[] without the annotation.

An assertion function is the throwing version. Its return type is asserts value is Type: if it returns at all, the value is narrowed for the rest of the scope.

function assertIsDefined<T>(value: T, name: string): asserts value is NonNullable<T> {
  if (value === null || value === undefined) {
    throw new Error(`${name} is required`);
  }
}
 
const apiKey = process.env.API_KEY;   // string | undefined
assertIsDefined(apiKey, "API_KEY");
apiKey.length;                        // string from here on

in narrowing in depth, and satisfies with unions

The table above lists in as "objects by property". Two details decide whether it narrows the way you expect.

Optional properties keep both members. "permissions" in u narrows to the members where permissions is required or optional, because an optional property may be present. If one member declares permissions?: undefined as a way to say "never has it", the check does not remove that member:

type Admin = { name: string; permissions: string[] };
type Guest = { name: string; permissions?: undefined; expires: Date };
 
function show(u: Admin | Guest) {
  if ("permissions" in u) {
    u; // still Admin | Guest: a Guest may carry permissions: undefined
  }
}

The fix is to discriminate on something both members declare as a required literal (role: "admin" | "guest"), which is one more reason a shared tag beats property sniffing.

Unknown properties get added. Since TypeScript 4.9, in also works on objects whose type does not mention the key. After "id" in x, TypeScript treats x as object & Record<"id", unknown>, so you can read x.id and narrow it further. That makes hand-written guards on unknown data much shorter:

function readId(x: unknown): string | null {
  if (typeof x === "object" && x !== null && "id" in x && typeof x.id === "string") {
    return x.id; // string
  }
  return null;
}

satisfies keeps the narrow member. The satisfies operator (TypeScript 4.9+) checks that a value matches a type without changing the type TypeScript infers for it. With unions that difference matters a lot. Annotate a lookup table with a union type and every entry becomes the whole union, so you must narrow again on every read:

type Route = { kind: "page"; path: string } | { kind: "redirect"; to: string };
 
const annotated: Record<string, Route> = {
  home: { kind: "page", path: "/" },
  old: { kind: "redirect", to: "/" },
};
annotated.home.path; // Error: 'path' does not exist on type 'Route'
annotated.tyop;      // No error: any string key is allowed
 
const routes = {
  home: { kind: "page", path: "/" },
  old: { kind: "redirect", to: "/" },
} satisfies Record<string, Route>;
routes.home.path;    // OK: TypeScript knows home is the "page" member
routes.tyop;         // Error: there is no tyop key

With satisfies, each entry is still checked against Route (a typo in kind or a missing path is an error), but the variable keeps its exact shape. Use annotation when you want callers to treat every entry the same; use satisfies for config objects where you know which entry is which.

Narrowing that does not survive callbacks

Narrowing is a property of a place in your code, not of the value. When you create a function, TypeScript has to decide whether the narrowing at that line still holds whenever the function eventually runs. Sometimes it cannot promise that, and the narrowing is dropped.

type State = { user: { name: string } | null };
 
function greetLater(state: State) {
  if (state.user) {
    state.user.name; // fine here
 
    setTimeout(() => {
      console.log(state.user.name);
      // Error: 'state.user' is possibly 'null'.
    }, 1000);
  }
}

TypeScript is right to worry. By the time the timer fires, some other code may have set state.user = null. The check happened a second ago, on a different turn of the event loop. The same applies to forEach, map, event handlers and promise callbacks: TypeScript does not know when, or how often, a callback runs.

The rules in current TypeScript:

  • A const variable or a parameter that is never reassigned keeps its narrowing inside callbacks. Nothing can change what it points to.
  • A let variable keeps its narrowing in a callback only if the callback is created after the last assignment to it (TypeScript 5.4+). If there is any assignment later in the function, the narrowing is dropped.
  • A property path like state.user loses narrowing inside callbacks, because any code anywhere could write to that property.

The fix is almost always the same: copy the narrowed value into a const.

function greetLater(state: State) {
  const user = state.user;
  if (user) {
    setTimeout(() => console.log(user.name), 1000); // OK: user is a const
  }
}

That is not just a trick to silence the compiler. It changes the behaviour to "greet the user who was logged in when I checked", which is usually what you meant.

There is an opposite hole. TypeScript does not forget property narrowing after an ordinary function call, even though that function could have changed the property:

if (state.user !== null) {
  logout(state);       // sets state.user = null inside
  state.user.name;     // no error, but crashes at runtime
}

Resetting every narrowing after every call would make the language unbearable to use, so the team chose this trade-off on purpose. It is one of the few places where TypeScript is knowingly unsound. Mutation is where types and reality drift apart, which is another reason to prefer immutable updates.

Quick check
Which line is a compile error under strict?
function run(input: string | null, box: { value: string | null }) {
if (input !== null && box.value !== null) {
  [1, 2].forEach(() => input.length);     // line A
  [1, 2].forEach(() => box.value.length); // line B
  const v = box.value;
  [1, 2].forEach(() => v.length);         // line C
}
}
Need a nudge? A hint rules out a wrong answer.

Modelling async state as a discriminated union

The RequestState union above is the starting point. Real screens add two requirements, and the union handles both without extra booleans.

Keep showing old data while refetching. Users hate a list that flashes to a spinner on every refresh. Let the loading and error members optionally carry the previous data. Ignore late replies. If a request resolves after the user has already moved on, the reply should not overwrite the screen. Both rules fit naturally into a reducer, a pure function that takes the current state and an action and returns the next state:

TypeScript
type AsyncState<T, E = string> = | { status: "idle" } | { status: "loading"; previous?: T } | { status: "success"; data: T; fetchedAt: number } | { status: "error"; error: E; previous?: T }; type Action<T> = | { type: "fetch" } | { type: "resolve"; data: T; at: number } | { type: "reject"; error: string }; function reducer<T>(state: AsyncState<T>, action: Action<T>): AsyncState<T> { switch (action.type) { case "fetch": { const previous = state.status === "success" ? state.data : undefined; return { status: "loading", previous }; } case "resolve": if (state.status !== "loading") return state; // a late reply: ignore it return { status: "success", data: action.data, fetchedAt: action.at }; case "reject": if (state.status !== "loading") return state; return { status: "error", error: action.error, previous: state.previous }; }} function view(state: AsyncState<string[]>): string { switch (state.status) { case "idle": return "idle"; case "loading": return state.previous ? `refreshing (${state.previous.length} shown)` : "spinner"; case "success": return `${state.data.length} items`; case "error": return `error: ${state.error}`; }} let s: AsyncState<string[]> = { status: "idle" };const log = () => console.log(view(s));s = reducer(s, { type: "fetch" }); log();s = reducer(s, { type: "resolve", data: ["a", "b"], at: 1 }); log();s = reducer(s, { type: "fetch" }); log();s = reducer(s, { type: "reject", error: "timeout" }); log();s = reducer(s, { type: "resolve", data: ["late"], at: 2 }); log();
Output
Press Run (⌘ Enter) to see what happens.

The last line is the interesting one. A reply arrives while the state is error, not loading, so the reducer drops it. The union turned "which transitions are legal" into a few if statements that the compiler checks.

Legal transitions for AsyncState
idleloadingsuccesserrorfetchresolverejectfetchretry

currentwaitingdone

Nothing requested yet. The only legal action is fetch.

1/5

You do not always write this by hand. TanStack Query, for example, exposes a status field ("pending" | "error" | "success") and a separate fetchStatus ("fetching" | "paused" | "idle"), because "do I have data?" and "is a request in flight?" are two different questions. Its result type is a discriminated union too, so checking status === "success" narrows data to defined. Once you can model the union yourself, those library types read like plain English.

switch (true) narrowing

Sometimes the cases are not values of one field but a list of conditions. Before TypeScript 5.3 you wrote an if/else if ladder. Now switch (true) narrows too: each case expression is treated like an if condition, and the cases that came before it count as failed.

TypeScript
function describe(value: string | number | Date | null): string { switch (true) { case value === null: return "empty"; case typeof value === "string": return `text (${value.length} chars)`; case typeof value === "number" && value < 0: return `negative ${value.toFixed(1)}`; case typeof value === "number": return `number ${value.toFixed(1)}`; default: return `date ${value.toISOString().slice(0, 10)}`; }} console.log(describe(null));console.log(describe("hello"));console.log(describe(-3));console.log(describe(42));console.log(describe(new Date("2026-10-22T00:00:00Z")));
Output
Press Run (⌘ Enter) to see what happens.

In default, TypeScript has removed null, string and number, so value is Date and toISOString is allowed. Two cautions. Write the cases as positive checks: a negated case such as case typeof x !== "number": does not narrow the cases after it, so you will get "possibly unknown" errors where you did not expect them. And some teams find switch (true) harder to read than if chains; it shines when every branch returns, like the classifier above.

Quick check
In the default branch of describe above, what is the type of value?
Need a nudge? A hint rules out a wrong answer.
Match the pairs0/5 matched

Match the situation to the narrowing tool.

Choose an item, then its match on the other side.
ChallengeEasy

Area of a discriminated union

Shapes are a discriminated union: every member has a kind field that says which one it is.

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

Write area(shape: Shape): number. Use a switch on shape.kind and add an exhaustiveness check with never in the default branch.

{ kind: "rect", width: 3, height: 4 }    →  12
{ kind: "circle", radius: 1 }            →  3.14159...
TypeScript
type Shape = | { kind: "circle"; radius: number } | { kind: "rect"; width: number; height: number } | { kind: "triangle"; base: number; height: number }; function area(shape: Shape): number { // switch (shape.kind) { ... } return 0;}
ChallengeMedium

Write a type guard

Data from JSON.parse or fetch has no trustworthy type. Write a type predicate that checks it at runtime:

type User = { id: number; email: string; name?: string };
 
function isUser(value: unknown): value is User

Return true only when:

  • value is a non-null object (and not an array),
  • id is a number and email is a string,
  • name is either missing or a string.

Extra properties are allowed.

TypeScript
type User = { id: number; email: string; name?: string }; function isUser(value: unknown): value is User { return false;}
Key terms
union type
A | B: a value that is one of several types. You can only use what all members share until you narrow.
narrowing
TypeScript refining a union to a smaller type based on checks like typeof, in, instanceof and equality.
discriminated union
A union of object types that share a literal property (like kind) used to tell them apart.
exhaustiveness check
Assigning the leftover value to never so the compiler errors when a union member is not handled.
type predicate
A return type value is T on a boolean function, so callers get narrowing when it returns true.
assertion function
A function with return type asserts value is T that throws if the check fails and narrows otherwise.
control flow analysis
How TypeScript follows if, return, switch and assignments to work out a variable's type at each line.
reducer
A pure function (state, action) => nextState, a natural home for the legal transitions of a discriminated union.