Wrap Storage with Typed Keys and Values

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

The problem

  • medium
  • Code
  • Pro

Write createStorage<Schema>(storage), where Schema maps each key to the type of value kept under it and storage is anything with getItem, setItem and removeItem (like localStorage, passed in so it can be tested). It returns get(key), set(key, value) and remove(key): values are stored as JSON, and get returns null for a missing key or text that isn't valid JSON. Type it so unknown keys are rejected, set only takes the key's own type, and get returns that type or null.

Your code must pass

  • Stores values as JSON and reads them back
  • Returns null for missing or broken values
  • Removes a value
  • Has no type errors
  • get returns the key's type or null
  • Rejects the wrong value for a key
  • Rejects an unknown key