Command Palette

Search for a command to run...

Hectal
Phase 13: TypeScript in the Browser: DOM and Async
TypeScript · Exercise 6 of 6 Previous
Advanced

Build a typed store and a counter page

Write a generic createStore<S>(initial: S) that returns an object with get(): S, set(update: (prev: S) => S): void and subscribe(listener: (state: S) => void): () => void. Calling the function subscribe returned removes the listener.

Use it: a store of { count: number }. Subscribe once so that the paragraph #out always shows count <n>. The button #inc adds one to the count when clicked.

Show the initial value on the page as well, so before any click it says count 0.

What Check tests

  1. Your code has no type errors
  2. The page starts at count 0
  3. Two clicks make it count 2
  4. The state type flows through set
  5. A wrong update type is rejected
  6. subscribe returns a function that stops the listener

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.