Module lessons (3/3)
Fetch API, JSON Unknown and Runtime Validation
Why res.json() is not enough on its own and how to validate arbitrary JSON responses with type-safe decoders.
What you'll learn in this lesson
- Understand why TypeScript types disappear before runtime and therefore never protect from malformed API payloads.
- Always check
res.ok(andres.status) before decoding the JSON body of an HTTP response. - Type the boundary between network/storage and application as
unknowninstead ofany(JSON.parse/res.json()). - Write compositional decoder / parser functions with type guard to transform
unknowndata into guaranteed domain types.
Overview
One of the most dangerous myths among TypeScript beginners is that writing const user: User = await res.json(); actually checks that the server sent id: number and email: string. Actually, in JavaScript res.json() returns Promise<any>: if the backend changes schema or sends an HTML error, TypeScript can't protect you if you don't check at…
A decoder receives unknown, checks each requested property at runtime, and returns the strong type (or throws a friendly error, or returns null / Result).
Sections covered in this lesson
- 1The HTTP border: check
res.okandunknown - 2Building Compound Decoders on
unknown - 3Guided practice
- 4Check for understanding
Unlock "Fetch API, JSON Unknown and Runtime Validation" and the full Course TypeScript curriculum
Why res.json() is not enough on its own and how to validate arbitrary JSON responses with type-safe decoders.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course TypeScript plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.