← React / TypeScript

React / TypeScript · 19 / 24

TypeScript: generics and discriminated unions

Model loading states without contradictory combinations and check exhaustive handling.

  • Large
  • Advanced
  • 90 min

Prerequisites: TypeScript types and modules

In this tutorial
  1. Understand the state model
  2. Start the project
  3. Verify the contract with a test
  4. Observe failures and boundaries
  5. Implement the exercise
  6. Verify the solution
  7. Exercise and solution
  8. Project context and sources

Download learning package

Setup and verification

Node.js 22.23 or newer with npm. Python 3 is also required for the common verification entry point. Extract the learning package into a new folder and run python3 run_checks.py there. The script copies the included files into a temporary learning directory. It verifies the example and then the supplied solution there, preserving the original files. Required packages are downloaded on the first run.

Verified on 2026-10-20 on Linux x86_64. Check valid and empty data. The solution adds another state. Both the compiler and the UI must handle it. A type assertion would only hide missing handling.

Independent boolean flags permit contradictory states. A union instead represents exactly one variant. A generic parameter keeps the payload type open. The compiler checks your code, but external JSON responses still require runtime validation.

Package contents and individual files

01Understand the state model

A generic type preserves the relationship between input and result. A discriminated union uses a shared kind field to distinguish states. An exhaustive switch exposes newly added states at compile time.

src/App.tsx · typescriptOpen file
import { useState } from "react";
export type Load<T> =
  | { kind: "idle" }
  | { kind: "loading" }
  | { kind: "ready"; data: T }
  | { kind: "error"; message: string };
function unreachable(value: never): never {
  throw new Error(`Unexpected state: ${JSON.stringify(value)}`);
}
export function describe<T>(
  state: Load<T>,
  render: (data: T) => string,
): string {
  switch (state.kind) {
    case "idle":
      return "Not loaded";
    case "loading":
      return "Loading";
    case "ready":
      return render(state.data);
    case "error":
      return state.message;
    default:
      return unreachable(state);
  }
}
export default function App() {
  const [state, setState] = useState<Load<string[]>>({ kind: "idle" });
  return (
    <main>
      <h1>Vehicle states</h1>
      <p role="status">{describe(state, (rows) => rows.join(", "))}</p>
      <button onClick={() => setState({ kind: "ready", data: ["Family car"] })}>
        Load example
      </button>
    </main>
  );
}

02Start the project

Install the pinned dependencies and run npm run dev. Data consists of synthetic learning values. Open the local address and trigger the action yourself.

package.json · jsonOpen file
{
  "name": "appfabrik-learning",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite --host 127.0.0.1",
    "build": "tsc --noEmit && vite build",
    "test": "vitest run src"
  },
  "dependencies": {
    "react": "19.2.3",
    "react-dom": "19.2.3",
    "react-router-dom": "7.18.4",
    "@tanstack/react-query": "5.104.5"
  },
  "devDependencies": {
    "vite": "8.1.5",
    "typescript": "6.0.3",
    "@types/react": "19.2.14",
    "@types/react-dom": "19.2.3",
    "@types/node": "22.19.15",
    "vitest": "4.1.10",
    "@testing-library/react": "16.3.2",
    "@testing-library/user-event": "14.6.1",
    "jsdom": "29.1.1",
    "@playwright/test": "1.64.1"
  }
}

03Verify the contract with a test

Check valid and empty data. The solution adds another state. Both the compiler and the UI must handle it. A type assertion would only hide missing handling.

src/App.test.tsx · typescriptOpen file
import { test, expect } from "vitest";
import { describe, type Load } from "./App";
test("all variants have a meaningful representation", () => {
  expect(describe({ kind: "idle" }, String)).toBe("Not loaded");
  expect(describe({ kind: "loading" }, String)).toBe("Loading");
  expect(
    describe({ kind: "ready", data: [1, 2] }, (rows) => rows.join(",")),
  ).toBe("1,2");
  expect(describe({ kind: "error", message: "Offline" }, String)).toBe(
    "Offline",
  );
});
// @ts-expect-error A ready state requires data.
const missing: Load<string> = { kind: "ready" };
void missing;

Run / check

npm install
npm test
npm run build
Expected result

Check valid and empty data. The solution adds another state. Both the compiler and the UI must handle it. A type assertion would only hide missing handling.

04Observe failures and boundaries

Change the expected output and observe a failed test. A TypeScript build protects type contracts while a browser test protects interactions. The two checks serve different purposes.

05Implement the exercise

Add an empty variant and handle it explicitly.

06Verify the solution

The solution extends both the type and switch. Temporarily remove the new case. tsc must fail at the never contract. This protects future additions as well. Copy the solution files to the corresponding locations in the learning project and run tests and build again.

Expected result

Tests and type checking pass. The observed result matches the learning goal.

Your exercise

Add an empty variant and handle it explicitly.

Show the solution and explanation

The solution extends both the type and switch. Temporarily remove the new case. tsc must fail at the never contract. This protects future additions as well.

solution/App.tsx · typescriptOpen file
import { useState } from "react";
export type Load<T> =
  | { kind: "empty" }
  | { kind: "idle" }
  | { kind: "loading" }
  | { kind: "ready"; data: T }
  | { kind: "error"; message: string };
function unreachable(value: never): never {
  throw new Error(`Unexpected state: ${JSON.stringify(value)}`);
}
export function describe<T>(
  state: Load<T>,
  render: (data: T) => string,
): string {
  switch (state.kind) {
    case "empty":
      return "No vehicles";
    case "idle":
      return "Not loaded";
    case "loading":
      return "Loading";
    case "ready":
      return render(state.data);
    case "error":
      return state.message;
    default:
      return unreachable(state);
  }
}
export default function App() {
  const [state, setState] = useState<Load<string[]>>({ kind: "idle" });
  return (
    <main>
      <h1>Vehicle states</h1>
      <p role="status">{describe(state, (rows) => rows.join(", "))}</p>
      <button onClick={() => setState({ kind: "ready", data: ["Family car"] })}>
        Load example
      </button>
    </main>
  );
}
solution/App.test.tsx · typescriptOpen file
import { test, expect } from "vitest";
import { describe, type Load } from "./App";
test("all variants have a meaningful representation", () => {
  expect(describe({ kind: "empty" }, String)).toBe("No vehicles");
  expect(describe({ kind: "idle" }, String)).toBe("Not loaded");
  expect(describe({ kind: "loading" }, String)).toBe("Loading");
  expect(
    describe({ kind: "ready", data: [1, 2] }, (rows) => rows.join(",")),
  ).toBe("1,2");
  expect(describe({ kind: "error", message: "Offline" }, String)).toBe(
    "Offline",
  );
});
// @ts-expect-error A ready state requires data.
const missing: Load<string> = { kind: "ready" };
void missing;

Project context and sources

This independent learning project explores a topic in this technology area. Project references provide a pinned revision as architectural context. They do not imply that every library or feature introduced here is already used in that application.