×

typescript · level 3 · unit 6 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Make the checker prove you handled every case.

Unions grow. Next month someone adds a gift card to Payment, and every switch that forgot it quietly does nothing. An turns that silence into an error you cannot miss.

After the last case, add a , which runs when nothing matched, and store the value in a box of type never. If every member was handled, nothing is left, so it fits. If one was missed, the checker reports TS2322 and names the member you forgot.

type Payment = { kind: "card" } | { kind: "cash" };
function fee(payment: Payment): number {
  switch (payment.kind) {
    case "card":
      return 0.2;
    case "cash":
      return 0;
    default:
      const unreachable: never = payment;
      return unreachable;
  }
}
console.log(fee({ kind: "card" }));

never fits in any box, so return unreachable is allowed whatever the return type.