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
- Define response interfaces:
interface UserResponse { id: number; name: string; } - Type the fetch function:
async function getUser(id: number): Promise<UserResponse> { ... } - Use generics for reusable fetch wrappers:
async function fetchJson<T>(url: string): Promise<T>. - Validate responses with a schema library before casting.
- 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
unknownas 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
anyremove the safety benefit of typed wrappers.