Subscribe to a Typed Slice of a Store

Write the code, see it run, pass the checks.

The problem

  • medium
  • Code
  • Pro

Write a class Store<S>, created with an initial state object. getState() returns the current state. setState(update) takes either a partial state or an updater function (state => partial state) and merges the result into a new state object. select(selector, listener) watches one slice of the state: after each setState it runs selector on the new state and, only if the result changed (compared with Object.is), calls listener(value, previous); it returns a function that stops watching. Type it so updates must match the state's fields and types, and listeners get the selector's result type.

Your code must pass

  • Merges partial updates and updater results
  • Calls a listener only when its slice changes
  • Stops calling a listener after unsubscribing
  • Has no type errors
  • getState returns the state type
  • setState takes a typed partial or updater
  • Listeners get the selector's result type