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
- Your code has no type errors
- The page starts at count 0
- Two clicks make it count 2
- The state type flows through set
- A wrong update type is rejected
- 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.