Read Search Params into a Typed Object

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

The problem

  • medium
  • Code

Write readParams(search, defaults): read a query string like ?page=2&tags=a&tags=b into an object with the same keys as defaults, each read by its default's type. A number param must be a finite number, a boolean one true or false, a string one is taken as it is, and an array of strings collects every value of that name; a missing or invalid param keeps its default, and params not in defaults are ignored. Type it so the result has each default's type (widened, so page: 1 gives number), and defaults can't hold anything else, such as objects or arrays of numbers.

Your code must pass

  • Reads each param by its default's type
  • Falls back to defaults for missing or invalid values
  • Has no type errors
  • Each param has its default's type
  • Rejects defaults of other types