Programming paths / TypeScript

TypeScript learning path

Use TypeScript to make application states, API boundaries, and large JavaScript codebases easier to maintain.

Starter lesson

Represent loading and error states as a union

A discriminated union prevents impossible combinations, such as a screen being both loading and failed. Narrow on the discriminant before reading the matching field.

type LoadState<T> =
  | { status: "loading" }
  | { status: "ready"; value: T }
  | { status: "failed"; message: string };

function describe(state: LoadState<string>): string {
  switch (state.status) {
    case "loading":
      return "Loading";
    case "ready":
      return state.value;
    case "failed":
      return `Could not load: ${state.message}`;
  }
}

What to expect

Each state carries only the data that is valid for that state.

Key idea: Use types to encode application states, but validate external data at runtime because types are erased.

← Browse all programming paths