Skip to article content
FrontendXLesson 05 / 40

Type guards and discriminated unions

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.

intermediate · about 45 minutes · 4 exercises

  • Implement
  • Debug
  • Interview

What you will be able to do

#
  • Write a custom type guard with a `value is T` return type.
  • Model state with a discriminated union.
  • Handle every variant with an exhaustive switch.

Overview

#

Custom type guards

A type guard is a normal function whose return type is value is T. The body performs a real runtime check; the return type teaches the checker.

snippet.ts
interface Cat { meow(): void }
interface Dog { bark(): void }

function isCat(animal: Cat | Dog): animal is Cat {
  return "meow" in animal;
}

After if (isCat(a)), a narrows to Cat.

Discriminated unions

Give every member a shared literal field. That field becomes the key the checker can narrow on.

snippet.ts
type Result<T> =
  | { status: "ok"; value: T }
  | { status: "error"; message: string };

A switch on status narrows each branch precisely, including value and message.

Exhaustiveness

Pass the remaining value to a never-typed helper in the default branch. If a new variant is added, that call stops compiling, which is exactly the reminder you want.

Guard honesty

A guard is a promise. If the body returns true for a value that is not really T, the checker trusts you and downstream code can fail at runtime. Keep the runtime test and the declared type in agreement.

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 1Implement

    Given `type Result<T> = { status: "ok"; value: T } | { status: "error"; message: string }`, implement `unwrap<T>(result: Result<T>): T` that returns the value or throws with the message.

    starter.typescript
    export type Result<T> =
      | { status: "ok"; value: T }
      | { status: "error"; message: string };
    
    export function unwrap<T>(result: Result<T>): T {
      // your code
    }
    

    Reveal the reference answer
    reference.typescript
    export type Result<T> =
      | { status: "ok"; value: T }
      | { status: "error"; message: string };
    
    export function unwrap<T>(result: Result<T>): T {
      if (result.status === "ok") return result.value;
      throw new Error(result.message);
    }
    

    Authored expected output: Compiles with no errors. Runtime: unwrap({ status: "ok", value: 1 }) is 1; unwrap({ status: "error", message: "bad" }) throws Error("bad").

    The discriminant status narrows each branch so value and message are available.

  2. Exercise 2Implement

    Write a type guard `isStringArray(value: unknown): value is string[]` that returns true only when every element is a string.

    starter.typescript
    export function isStringArray(value: unknown): value is string[] {
      // your code
    }
    

    Reveal the reference answer
    reference.typescript
    export function isStringArray(value: unknown): value is string[] {
      return Array.isArray(value) && value.every((item) => typeof item === "string");
    }
    

    Authored expected output: Compiles with no errors. Runtime: isStringArray(["a"]) is true, isStringArray(["a", 1]) is false, isStringArray("a") is false.

    Array.isArray narrows to unknown[], and every narrows each element before the guard returns.

  3. Exercise 3Debug

    This compiles but is unsafe at runtime. Fix the guard so its promise is true. ```ts function isNumber(value: unknown): value is number { return true; } ```

    starter.typescript
    function isNumber(value: unknown): value is number {
      return true;
    }
    

    Reveal the reference answer
    reference.typescript
    function isNumber(value: unknown): value is number {
      return typeof value === "number" && Number.isFinite(value);
    }
    

    Authored expected output: Compiles with no errors. Runtime: isNumber(1) is true, isNumber("1") is false, isNumber(NaN) is false.

    A guard must actually test the value; returning true unconditionally lies to the checker.

  4. Exercise 4Interview

    You are reviewing a data-fetching layer. Explain how you would model loading, success and error states so that impossible combinations cannot be represented, and how the UI would consume them.

    Reveal the reference answer
    reference.typescript
    Model a discriminated union with a literal status on each member: loading with no payload, success with data, error with a message. Because each member carries only the fields valid for that state, a component that switches on status gets the right payload and cannot read data while loading. Add a never-typed default branch so a new state forces every switch to be updated.

    Authored expected output: A design answer naming a discriminated union, the status key and exhaustive switching.

    The union makes invalid states unrepresentable, which removes a whole class of runtime bugs.

Common misconceptions

#
  • A type guard validates the value at runtime automatically.
  • Discriminated unions need classes.
  • A default branch makes a switch exhaustive.

Follow-up practice

#
  • typescript-functions-overloads

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.