Lesson 3.2

Typing async boundaries and API responses

Asserting a fetch result into an interface tells the compiler what you hope arrived.

36mIntermediate15.3k students

Overview

Your types stop at the network

Asserting a fetch result into an interface tells the compiler what you hope arrived. The server can change tomorrow and the types will keep insisting everything is fine, right up until a property is undefined in production.

Parse instead of assert. Validate the payload at the boundary and let the parsed result carry the type, so a schema change surfaces as a caught validation error with a useful message.

Where failure is expected, return it rather than throwing. A result type that forces the caller to handle the error branch is checked; a thrown error is a comment.

In this lesson you will:

  • Stop trusting a response body by assertion
  • Model failure as part of the return type
  • Keep generated API types in sync

Resources

Previous Lesson
Next Lesson
Typing async boundaries and API responses — TypeScript Deep Dive — Vertex