Skip to article content
FrontendXLesson 03 / 40

Union types and narrowing

Go from the first annotated variable to writing your own conditional, mapped and infer-based utility types, while keeping a clear line between compile-time checking and runtime behavior.

beginner · about 45 minutes · 4 exercises

  • Predict
  • Implement
  • Debug
  • Test

What you will be able to do

#
  • Read a union type and describe the values it allows.
  • Narrow with typeof, truthiness, equality and Array.isArray.
  • Recognize where control-flow narrowing is lost.

Overview

#

Unions describe alternatives

snippet.ts
type Id = string | number;

A value of type Id is one of the members, not both. To use member-specific behavior you narrow the type inside a branch.

Narrowing tools

snippet.ts
function label(id: Id): string {
  if (typeof id === "number") return id.toFixed(0);
  return id.trim();
}

Control-flow analysis tracks the type in each branch. typeof, truthiness, ===/!==, in, instanceof and Array.isArray all narrow.

snippet.ts
function describe(value: string | string[] | null): string {
  if (value === null) return "empty";
  if (Array.isArray(value)) return value.join(", ");
  return value.toUpperCase();
}

Where narrowing is lost

Narrowing does not survive into callbacks that run later, because the checker cannot prove the variable is unchanged by then.

snippet.ts
function run(value: string | undefined) {
  if (value === undefined) return;
  setTimeout(() => {
    // value is string | undefined again here
  }, 0);
}

Assign the narrowed value to a new const before the callback.

Discriminated unions preview

When every member shares a literal field, that field becomes the switch key. That pattern is covered in a later lesson.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    What does this print at runtime, and does it compile? ```ts function f(v: string | number) { if (typeof v === "string") return v.length; return v.toFixed(1); } console.log(f("abc"), f(2)); ```

    Choose the best answer
  2. Exercise 2Implement

    Implement `formatValue(value: string | number | boolean | null): string` returning the string itself, the number as text, "yes"/"no" for booleans and "none" for null.

    starter.typescript
    export function formatValue(value: string | number | boolean | null): string {
      // your code
    }
    

    Reveal the reference answer
    reference.typescript
    export function formatValue(value: string | number | boolean | null): string {
      if (value === null) return "none";
      if (typeof value === "boolean") return value ? "yes" : "no";
      if (typeof value === "number") return String(value);
      return value;
    }
    

    Authored expected output: Compiles with no errors. Runtime: formatValue("a") is "a", formatValue(1) is "1", formatValue(true) is "yes", formatValue(null) is "none".

    Each branch removes one member from the union until only string remains.

  3. Exercise 3Debug

    This fails to compile. Fix it so the callback can use the narrowed value. ```ts function schedule(value: string | undefined) { if (value === undefined) return; setTimeout(() => console.log(value.toUpperCase()), 0); } ```

    starter.typescript
    function schedule(value: string | undefined) {
      if (value === undefined) return;
      setTimeout(() => console.log(value.toUpperCase()), 0);
    }
    

    Reveal the reference answer
    reference.typescript
    function schedule(value: string | undefined) {
      if (value === undefined) return;
      const text = value;
      setTimeout(() => console.log(text.toUpperCase()), 0);
    }
    

    Authored expected output: Compile error resolved: 'value' is possibly 'undefined'. The captured const keeps the narrowed string type.

    Narrowing does not cross into a deferred callback, so capture the narrowed value first.

  4. Exercise 4Test

    Write a function `assertNever(value: never): never` that throws, then use it in a switch over a union of three string literals so a missing case fails to compile.

    starter.typescript
    type Status = "idle" | "loading" | "done";
    
    export function assertNever(value: never): never {
      throw new Error("unexpected: " + String(value));
    }
    
    export function describe(status: Status): string {
      // your code
    }
    

    Reveal the reference answer
    reference.typescript
    type Status = "idle" | "loading" | "done";
    
    export function assertNever(value: never): never {
      throw new Error("unexpected: " + String(value));
    }
    
    export function describe(status: Status): string {
      switch (status) {
        case "idle": return "waiting";
        case "loading": return "working";
        case "done": return "finished";
        default: return assertNever(status);
      }
    }
    

    Authored expected output: Compiles with no errors. Removing one case makes the default branch fail: Argument of type '"done"' is not assignable to parameter of type 'never'.

    The never parameter converts a forgotten case into a compile-time error.

Common misconceptions

#
  • A union means a value has all members at once.
  • Narrowing persists inside any callback.
  • typeof narrows arrays to a distinct type.

Follow-up practice

#
  • typescript-objects-interfaces

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.