← All Exercises

Typed JSON Fetch with Validation

intermediatetypescript~15min

Background

Fetching JSON usually ends with an unchecked type assertion. Combining a runtime type guard with a generic return type keeps validation and static typing in sync while separating transport errors from payload errors.

Problem

Implement fetchJson<T>(url, validate, request) where request returns a response-like object. Throw HttpError for non-2xx statuses, JsonError('INVALID_JSON') for unparsable text, and JsonError('INVALID_SHAPE') when the validator rejects the parsed value. On success, return the value typed as T.

Input

A JSON object with url, status, and body; the body is returned verbatim by the injected request function.

Output

A JSON object with ok:true and the validated value, or ok:false and an error code such as HTTP_404, INVALID_JSON, or INVALID_SHAPE.

Sample tests

Sample 1

Input: {"url":"/api/user","status":200,"body":"{\"id\":1,\"name\":\"Ada\"}"}
Expected: {"ok":true,"value":{"id":1,"name":"Ada"}}

Sample 2

Input: {"url":"/api/user","status":404,"body":""}
Expected: {"ok":false,"error":"HTTP_404"}

Sample 3

Input: {"url":"/api/user","status":200,"body":"{\"id\":\"x\"}"}
Expected: {"ok":false,"error":"INVALID_SHAPE"}

Sample 4

Input: {"url":"/api/user","status":200,"body":"not json"}
Expected: {"ok":false,"error":"INVALID_JSON"}

Your solution

Learning objective

Combine generics, type guards, custom errors, and dependency injection in async code.