Model a tiny API layer with types end-to-end: request params, success payload, and error shape.
Steps
- Define
ApiResult<T>as a discriminated union. - Implement
fetchUser(id: string)returning mock data. - Print a friendly message for success and failure.
Extension ideas
- Add timeout and retry types
- Map HTTP status codes to typed errors
- Validate mock JSON with a schema before trusting
data
Self-check
- Draw your
ApiResult<T>union on paper with two branches.
In production, pair this pattern with runtime validators at the network boundary so types cannot lie about JSON shape.
Go deeper — Production API typing
At boundaries, validate JSON with zod or similar—types alone do not prove runtime shape.
Challenge
Typed fetch mock
- Define
ApiResult<T>success/failure union. - Parse a mock JSON object and narrow on
ok.
Done when: terminal prints data or error branch only after narrowing.