Command Palette

Search for a command to run...

Hectal
Phase 12: TypeScript with React
React · Exercise 3 of 5 PreviousNext
Intermediate

A score keeper with typed actions

The score keeper's reducer takes action: any and only handles adding points. Type it properly and finish it.

Write type Action as a discriminated union of { type: "add"; points: number }, { type: "undo" } and { type: "reset" }. Type the state as { score: number; history: number[] } (history holds the points of each add, newest last).

Handle every action in a switch, with a default branch that assigns action to a variable of type never. Undo removes the last add; Reset goes back to 0 with an empty history.

Keep the ids: id="score", buttons id="plus1", id="plus5", id="undo", id="reset".

What Check tests

  1. +1 then +5 shows 6
  2. Undo removes the last add (back to 1)
  3. Undo with an empty history does nothing
  4. Reset goes back to 0 after more adds
  5. Actions are a discriminated union
  6. Uses a switch with a never check and no any

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

Runs in your browser. Your code is saved here.

Your page

Press Run to see the page.

Console

Nothing logged yet.