Parse JSON Safely into a Checked Shape

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

The problem

  • medium
  • Code

Write safeJsonParse(text), which never throws: it returns { ok: true, value } with the parsed value, or { ok: false, error } with a message when the text isn't valid JSON. Then write parseAs(text, guard), which parses the text and also checks the value with a type guard you pass in, returning ok: false with a message when the shape is wrong. Type the parsed value as unknown (it could be anything), have parseAs return the guard's type, and only let callers read value after checking ok.

Your code must pass

  • Parses valid JSON
  • Returns an error for invalid JSON instead of throwing
  • parseAs rejects JSON of the wrong shape
  • Has no type errors
  • The parsed value is unknown
  • parseAs narrows to the guard's type
  • value can't be read before checking ok