Bitpath

Lesson 2 · Unit 08

Designing with types

Shape your types so that wrong states cannot be written down

13 exercisesabout 3 min

What you practise

  • States that cannot be wrong because the types forbid them, as const, unions against enums, the never check that every case is handled, type guards

Try a question from this lesson

Pick one

This value says a request is still loading, has its data, and has failed, all at once. Does the compiler object?

TypeScript
type Load = {
  loading: boolean;
  data?: string;
  error?: string;
};
const r: Load = {
  loading: true, data: "hi", error: "no",
};

The ideas

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

Concept

Only the states that exist

Instead of one shape with optional parts, write a union: one shape per real state, each with a state property that names it.

Now data without "done", or an error while loading, cannot even be written down. The nonsense combinations are not handled. They are gone.

TypeScript
type Load =
  | { state: "loading" }
  | { state: "done"; data: string }
  | { state: "failed"; error: string };

const a: Load = { state: "loading" };
const b: Load = {
  state: "done", data: "hi",
};

Concept

The never tripwire

When every case has returned, no value is left. The compiler gives what remains the type never: "cannot happen".

Assigning it to a never variable sets a tripwire. Add a third colour to Light one day, and that line stops compiling until this function handles it.

TypeScript
type Light = "red" | "green";

function next(l: Light): Light {
  if (l === "red") return "green";
  if (l === "green") return "red";
  const left: never = l;
  return left;
}

Concept

as const

The compiler widens: a value that could change later gets the general type, string, not the exact text.

as const says: this will never change, keep the exact values. Properties get literal types and become readonly. It is how plain data keeps up with literal unions.

TypeScript
let a = "left";    // type: string
const b = "left";  // type: "left"

const c = { dir: "left" };
// c.dir has type string

const d = { dir: "left" } as const;
// d.dir has type "left", and is readonly

9 more exercises in the app

  • 3× multiple choice
  • 3× type the answer
  • 1× true or false
  • 1× fill the blanks
  • 1× match the pairs

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