Fetch JSON into a Validated Type

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

The problem

  • hard
  • Code
  • Pro

Write getJson(fetchLike, url, validate): call fetchLike(url) (a fetch-like function passed in, so no real network), read the body as JSON and check it with validate, a type guard. Never throw: resolve to { ok: true, value } or { ok: false, error }, where error is { kind: network } if the call fails, { kind: status, status } for a response that isn't ok, and { kind: invalid } for a body that isn't JSON or fails validate. Export FetchError and FetchResult<T> for these, typed so value has the guard's type and can only be read after checking ok, and validate must be a type guard, not just any function returning a boolean.

Your code must pass

  • Returns the validated value
  • Reports network and status errors
  • Reports bad JSON and data that fails validation
  • Has no type errors
  • value has the validated type once ok
  • Errors say what went wrong
  • validate must be a type guard