TypeDrop
2026-10-13 Challenge
2026-10-13
Easy
Typed Safe JSON Parser with Result Type
You're building the API response layer for a mobile app backend. Raw JSON arrives over the wire and must be safely parsed and narrowed into one of several known response shapes — the compiler must enforce that callers always handle both the success and failure paths, and that the typed payload is only accessible after a successful parse.
Goals
- Define a generic `Result<T, E>` discriminated union and a `ParseError` discriminated union with two variants each.
- Implement a type guard `isApiPayload` that narrows `unknown` to `ApiPayload` by checking all required fields per `kind`.
- Implement `parseApiResponse` that returns a typed `Result` — never throwing, always returning ok or error.
- Implement `describePayload` with an exhaustive switch over `ApiPayload` kinds, using a `never` assertion in the default branch.
challenge.ts
// Core types you must define and implement:
type Result<T, E> =
| { ok: true; value: T }
| { ok: false; error: E };
type ParseError =
| { reason: "invalid-json"; raw: string }
| { reason: "unknown-shape"; parsed: unknown };
type ApiPayload = UserPayload | OrderPayload | ErrorPayload;
// Main functions to implement:
function isApiPayload(value: unknown): value is ApiPayload { ... }
function parseApiResponse(raw: string): Result<ApiPayload, ParseError> { ... }
function describePayload(payload: ApiPayload): string { ... }
Hints (click to reveal)
Hints
- For `isApiPayload`, check `typeof value === 'object' && value !== null` first, then use `'kind' in value` before narrowing further — no casting needed.
- In the `default` branch of `describePayload`, assign the payload to a variable typed as `never` to get a compile-time exhaustiveness check: `const _exhaustive: never = payload`.
- In `parseApiResponse`, wrap `JSON.parse` in a try/catch — the caught value is `unknown`, so you don't need to inspect it, just return the `invalid-json` error variant.
Useful resources
Or clone locally
git clone -b challenge/2026-10-13 https://github.com/niltonheck/typedrop.git