Skip to main content
Module 8 · Lesson 3 of 317/22 in the course~18 min
Module lessons (3/3)

Fetch API, JSON Unknown and Runtime Validation

Lesson preview5 hands-on exercises readyCourse TypeScript · Module 8 — TypeScript Asynchronous & Promise

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 (and res.status) before decoding the JSON body of an HTTP response.
  • Type the boundary between network/storage and application as unknown instead of any (JSON.parse / res.json()).
  • Write compositional decoder / parser functions with type guard to transform unknown data 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

  1. 1The HTTP border: check res.ok and unknown
  2. 2Building Compound Decoders on unknown
  3. 3Guided practice
  4. 4Check for understanding
Pro Lesson · Module 8 — TypeScript Asynchronous & Promise

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.