CHAPTER 9 · 1 lesson · 13 exercises

Design state with types

Loading / Empty / Error / Success — express the four states of a screen as a discriminated union and catch every missing case.

0 / 13 solved

An app that fetches data has four possible states for its screen.

  • loading — data is on its way; show a spinner
  • success — data arrived; show the list
  • empty — data arrived but there is nothing; show "nothing here yet"
  • error — the request failed; show "try again"

These four can be written as a type. Use the discriminated union from chapter 3. Give every branch a shared status tag and line up four shapes with |.

switch (state.status) branches into four, and inside each case TypeScript narrows the type. state.data is only available inside "success". state.message is only available inside "error".

Once you can write this, the type tells you which data exists in which state. "Reading data while still loading" or "showing a list during an error" becomes impossible before you run anything.

This is the typed foundation for "fetch, receive, render" in the next phase.

Lessons in this chapter

Write the four states

  1. 37Design four states with typesLoading, success, empty, error — express the four states a screen can be in with a discriminated union.Go to the exercises

This is the last chapter of the course.