Bitpath

Boss lesson · Unit 01

Unions and narrowing

Model a request so that impossible states cannot be written

13 exercisesabout 3 min

What you practise

  • typeof, in and equality narrowing, a discriminated union for request states, the exhaustive switch that fails to compile when a case is added

Try a question from this lesson

Pick one

A request is loading, done or failed. Each field here is independently on or off. How many combinations can the type hold, and how many are real?

TypeScript
interface Req {
  loading: boolean;
  data?: string[];
  error?: string;
}
Hint

Three yes/no facts: loading or not, data or not, error or not.

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Unions and narrowing

A | B is a value that is an A or a B. Until you know which, you may only use what both have.

A check the compiler understands, like typeof, narrows the type inside the branch. After a return, the rest of the function knows the check failed.

TypeScript
function show(id: number | string) {
  // id.toFixed(1) here: rejected
  if (typeof id === "number") {
    return id.toFixed(1);   // number
  }
  return id.toUpperCase();  // string
}

Concept

Discriminated unions

Give every case a property with a different literal type: a tag. Checking the tag tells the compiler which case it holds, and so which other fields exist.

This is the request from before with only its 3 real states. "Loading with an error" can no longer be written.

TypeScript
type Req =
  | { kind: "loading" }
  | { kind: "ok"; data: string[] }
  | { kind: "error"; message: string };

Concept

never: nothing is left

When every case has been ruled out, the value's type is never, the type with no values.

Assign what is left to a never in the default branch. Today it compiles. The day someone adds a fourth case, that line stops compiling and points at the switch that forgot it. Python's assert_never does the same for a type checker.

TypeScript
type Light = "red" | "green";
function go(l: Light): boolean {
  switch (l) {
    case "red": return false;
    case "green": return true;
    default:
      const left: never = l;
      return left;
  }
}

9 more exercises in the app

  • 2× fill the blanks
  • 3× multiple choice
  • 2× type the answer
  • 1× order the lines
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy