How to handle API response types in TypeScript

· Category: TypeScript

Short answer

Define interfaces for request and response shapes, type your fetch wrappers, and use runtime validation libraries like Zod or io-ts to ensure server data matches expectations.

Steps

  1. Define response interfaces: interface UserResponse { id: number; name: string; }
  2. Type the fetch function: async function getUser(id: number): Promise<UserResponse> { ... }
  3. Use generics for reusable fetch wrappers: async function fetchJson<T>(url: string): Promise<T>.
  4. Validate responses with a schema library before casting.
  5. Handle error responses with union types or custom error classes.

Tips

  • Derive request types from form or state interfaces to keep client and server contracts in sync.
  • Use unknown as the initial parse type and narrow with validation instead of blind type assertions.

Common issues

  • Trusting server responses without validation leads to runtime crashes when the API changes.
  • Generics that default to any remove the safety benefit of typed wrappers.