Creating Response Type Interfaces
What you'll learn: How to define TypeScript interfaces that exactly match your API's JSON structure, ensuring type safety when working with network data.
The Problem with Untyped API Responses
When you fetch data from an API, TypeScript doesn't magically know what shape that data will have. The fetch API returns Promise<Response>, and calling .json() returns Promise<any> — meaning you lose all type safety. This is where response type interfaces come in.
Defining Interfaces That Match JSON Structure
A response type interface is simply an interface that mirrors the exact structure of the JSON your API returns. Think of it as a contract between your API and your frontend code.
For example, if your API returns user data like this:
{
"id": 123,
"username": "alice",
"email": "alice@example.com",
"isActive": true
}
You create a matching interface:
interface UserResponse {
id: number;
username: string;
email: string;
isActive: boolean;
}
Why This Matters
Once you have this interface, you can use it consistently across your entire application. Every function that handles user data can reference UserResponse, giving you autocomplete, compile-time checking, and self-documenting code. If the API structure changes, you update the interface once, and TypeScript immediately shows you every place in your code that needs adjustment.
Nested Structures
APIs often return complex nested objects. Your interfaces should match this nesting exactly:
interface PostResponse {
id: number;
title: string;
author: {
id: number;
name: string;
};
tags: string[];
}
Key Takeaway: Response type interfaces are TypeScript's way of documenting and enforcing the exact shape of your API data, turning runtime surprises into compile-time errors and enabling powerful autocomplete across your codebase.