How to Use Generics in React Components :👈 👉:How to Create Type-Safe Reusable Form Components

How to Type API Responses in React

How to Type API Responses in React with TypeScript

1. Why Do We Need to Type API Responses?

When a React application calls an API, the server returns data, usually in JSON format.

For example, an API might return the following user information:

{
    "id": 1,
    "name": "John",
    "email": "john@example.com"
}

Without TypeScript types, it is difficult to know exactly what properties the API response contains.

By defining types or interfaces, we can:

  • Understand the structure of API responses.
  • Get IntelliSense and autocomplete in the editor.
  • Identify incorrect property names during development.
  • Reduce type-related programming mistakes.
  • Make API-related code easier to maintain.

2. Define an Interface for an API Response

The first step is to define an interface that represents the structure of the API response.

Example API response:

{
    "id": 1,
    "name": "John",
    "email": "john@example.com",
    "isActive": true
}

Define the TypeScript interface:

interface User {
    id: number;
    name: string;
    email: string;
    isActive: boolean;
}

Now TypeScript understands the structure of a User object.

Using the interface:

const user: User = {
    id: 1,
    name: "John",
    email: "john@example.com",
    isActive: true
};

If we provide an incorrect property type, TypeScript reports a type error during development.

3. Type API Responses Using fetch()

The browser's fetch() API returns a Promise containing a Response object.

We can use the json() method to read the response body.

However, TypeScript does not automatically know the structure of the returned JSON data. We should explicitly type or validate it.

Example:

interface User {
    id: number;
    name: string;
    email: string;
}
async function getUsers(): Promise<User[]> {
    const response = await fetch(
        "https://api.example.com/users"
    );
    if (!response.ok) {
        throw new Error("Failed to fetch users");
    }
    const users = await response.json() as User[];
    return users;
}

Explanation:

  • Promise<User[]> means the function returns a Promise that resolves to an array of User objects.
  • response.json() reads the JSON response body.
  • as User[] tells TypeScript to treat the parsed data as an array of User objects.
  • response.ok checks whether the HTTP status indicates success.

Important: The as User[] assertion does not validate the actual API response. It only tells the TypeScript compiler what type to assume.

4. Display Typed API Data in a React Component

Now let's use the typed API function inside a React component.

import { useEffect, useState } from "react";
interface User {
    id: number;
    name: string;
    email: string;
}
async function getUsers(): Promise<User[]> {
    const response = await fetch(
        "https://api.example.com/users"
    );
    if (!response.ok) {
        throw new Error("Failed to fetch users");
    }
    return response.json() as Promise<User[]>;
}
function UserList() {
    const [users, setUsers] = useState<User[]>([]);
    const [loading, setLoading] = useState<boolean>(true);
    const [error, setError] = useState<string | null>(null);
    useEffect(() => {
        async function loadUsers() {
            try {
                const data = await getUsers();
                setUsers(data);
            } catch (err) {
                setError(
                    err instanceof Error
                        ? err.message
                        : "Something went wrong"
                );
            } finally {
                setLoading(false);
            }
        }
        loadUsers();
    }, []);
    if (loading) {
        return <p>Loading users...</p>;
    }
    if (error) {
        return <p>Error: {error}</p>;
    }
    return (
        <ul>
            {users.map(user => (
                <li key={user.id}>
                    {user.name} - {user.email}
                </li>
            ))}
        </ul>
    );
}
export default UserList;

Important points:

  • useState<User[]>([]) defines the users state as an array of User objects.
  • useState<boolean>(true) defines the loading state as a boolean.
  • useState<string | null>(null) allows the error state to contain a string or null.
  • The API response is assigned to the state after the request succeeds.
  • The component handles loading, success, and error states separately.

5. Type API Responses with Optional Properties

Sometimes API responses contain properties that are optional or may be missing.

For example:

{
    "id": 1,
    "name": "John",
    "email": "john@example.com",
    "phone": null
}

We can represent optional and nullable properties in TypeScript.

interface User {
    id: number;
    name: string;
    email: string;
    phone?: string | null;
}

Here:

  • phone? means the property may be missing.
  • string | null means the property may contain a string or null.
  • Both conditions are supported because the property is optional and nullable.

Example:

function UserDetails({ user }: { user: User }) {
    return (
        <div>
            <p>{user.name}</p>
            <p>{user.phone ?? "Phone not available"}</p>
        </div>
    );
}

6. Type Nested API Responses

Real-world APIs often return nested objects and arrays.

Example API response:

{
    "id": 1,
    "name": "John",
    "address": {
        "city": "Hyderabad",
        "country": "India"
    },
    "orders": [
        {
            "orderId": 101,
            "amount": 2500
        },
        {
            "orderId": 102,
            "amount": 1500
        }
    ]
}

Define TypeScript interfaces:

interface Address {
    city: string;
    country: string;
}
interface Order {
    orderId: number;
    amount: number;
}
interface User {
    id: number;
    name: string;
    address: Address;
    orders: Order[];
}

Using the nested properties:

function UserDetails({ user }: { user: User }) {
    return (
        <div>
            <h2>{user.name}</h2>
            <p>
                {user.address.city},
                {user.address.country}
            </p>
            <h3>Orders</h3>
            {user.orders.map(order => (
                <p key={order.orderId}>
                    Order: {order.orderId}
                    - Amount: {order.amount}
                </p>
            ))}
        </div>
    );
}

Defining separate interfaces for nested objects makes the code easier to understand and reuse.

7. Type API Responses with Generic Types

Many APIs follow a common response structure.

For example:

{
    "success": true,
    "message": "Data retrieved successfully",
    "data": []
}

Instead of creating a separate response interface for every API, we can use generics.

Define a generic API response type:

interface ApiResponse<T> {
    success: boolean;
    message: string;
    data: T;
}

Here, T represents the actual data type returned by the API.

Example 1: User API

interface User {
    id: number;
    name: string;
}
type UserResponse = ApiResponse<User[]>;

Example 2: Product API

interface Product {
    id: number;
    name: string;
    price: number;
}
type ProductResponse = ApiResponse<Product[]>;

Example 3: Single user API

type SingleUserResponse = ApiResponse<User>;

This approach avoids repeating the same response structure for every API.

8. Create a Reusable Generic API Function

We can use generics to create a reusable function for calling different APIs.

async function apiGet<T>(url: string): Promise<T> {
    const response = await fetch(url);
    if (!response.ok) {
        throw new Error("API request failed");
    }
    return response.json() as Promise<T>;
}

Using the generic API function:

interface User {
    id: number;
    name: string;
}
interface Product {
    id: number;
    name: string;
    price: number;
}
async function loadData() {
    const users = await apiGet<User[]>(
        "/api/users"
    );
    const products = await apiGet<Product[]>(
        "/api/products"
    );
    console.log(users);
    console.log(products);
}

The same API function can be used for different response types.

Note: This generic function provides compile-time typing only. It does not check whether the server actually returned the expected data structure.

9. Handle API Loading, Success, and Error States with a Discriminated Union

Instead of maintaining separate loading, error, and data states, we can model the API request status using a discriminated union.

type ApiState<T> =
    | { status: "loading" }
    | { status: "success"; data: T }
    | { status: "error"; message: string };

Using it in a React component:

import { useEffect, useState } from "react";
interface User {
    id: number;
    name: string;
}
function UserList() {
    const [state, setState] = useState<ApiState<User[]>>({
        status: "loading"
    });
    useEffect(() => {
        async function loadUsers() {
            try {
                const response = await fetch("/api/users");
                if (!response.ok) {
                    throw new Error("Failed to load users");
                }
                const users =
                    await response.json() as User[];
                setState({
                    status: "success",
                    data: users
                });
            } catch (err) {
                setState({
                    status: "error",
                    message: err instanceof Error
                        ? err.message
                        : "Unknown error"
                });
            }
        }
        loadUsers();
    }, []);
    if (state.status === "loading") {
        return <p>Loading...</p>;
    }
    if (state.status === "error") {
        return <p>{state.message}</p>;
    }
    return (
        <ul>
            {state.data.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}

Advantages:

  • All API request states are represented in one variable.
  • Each state has only the properties it needs.
  • TypeScript understands which properties are available based on the status.
  • It reduces inconsistent combinations of loading, error, and data values.

10. Runtime Validation of API Responses

This is one of the most important concepts when working with TypeScript and APIs.

Consider this code:

const users = await response.json() as User[];

It tells TypeScript to assume that the response contains User objects. It does not verify the actual response.

For example, the server might accidentally return:

{
    "id": "wrong-type",
    "name": 123
}

TypeScript will not automatically detect this mismatch at runtime.

For reliable applications, validate external data using a runtime validation library such as Zod.

Example using Zod:

import { z } from "zod";
const UserSchema = z.object({
    id: z.number(),
    name: z.string(),
    email: z.string().email()
});
const UsersSchema = z.array(UserSchema);
type User = z.infer<typeof UserSchema>;
async function getUsers(): Promise<User[]> {
    const response = await fetch("/api/users");
    if (!response.ok) {
        throw new Error("Failed to fetch users");
    }
    const json: unknown = await response.json();
    return UsersSchema.parse(json);
}

How it works:

  1. Define the expected structure using a Zod schema.
  2. Read the API response as unknown.
  3. Validate the response using UsersSchema.parse().
  4. If the response matches the schema, validated data is returned.
  5. If the response does not match, Zod throws a validation error.

This provides both TypeScript type safety and runtime validation.

11. Common Mistakes

1. Using any for API Responses

Avoid:

const users: any = await response.json();

Better:

const users: unknown = await response.json();

Then validate the response or safely narrow its type before using it.

2. Assuming Type Assertions Validate Data

const user = await response.json() as User;

This is only a compile-time assertion. It does not validate the API response at runtime.

3. Ignoring Nullable Properties

If an API can return null, include it in the type.

interface User {
    id: number;
    name: string | null;
}

4. Ignoring HTTP Errors

fetch() does not automatically reject its Promise for HTTP error responses such as 404 or 500. Always check response.ok.

5. Repeating API Response Structures

When multiple APIs share a response format, use a generic response type instead of defining duplicate interfaces.

12. Best Practices

  • Define interfaces or types for API request and response data.
  • Use meaningful names such as User, Product, Order, and ApiResponse.
  • Use generics for reusable API functions and common response structures.
  • Use unknown rather than any when handling unvalidated external data.
  • Validate important external API responses at runtime.
  • Handle loading, success, and error states explicitly.
  • Represent optional and nullable properties accurately.
  • Keep API types separate from UI component code when the application grows.
  • Use a data-fetching library such as TanStack Query when caching, retries, request synchronization, and server-state management become important.

13. Interview Questions and Answers

Q1. Why do we need to type API responses in React?

Typing API responses helps maintain type safety, provides IntelliSense, identifies incorrect property access, and makes application code easier to maintain.

Q2. How do you define an API response type in TypeScript?

We can use an interface or type alias to describe the expected structure of the response.

interface User {
    id: number;
    name: string;
    email: string;
}

Q3. What does Promise<User[]> mean?

It means the function returns a Promise that resolves to an array of User objects.

Q4. Does response.json() automatically identify the response type?

No. The JSON parsing method does not automatically validate or establish the application's expected data structure. We need to provide type information or validate the data.

Q5. What is the difference between any and unknown?

any disables most type checking. unknown requires us to check or narrow the type before using the value.

Q6. What is a generic API response?

A generic API response is a reusable type that accepts different data types through a generic parameter.

interface ApiResponse<T> {
    success: boolean;
    data: T;
}

Q7. What is runtime validation?

Runtime validation checks whether actual data received from an API matches the expected structure. Libraries such as Zod can perform this validation.

Q8. How do you handle nullable API properties?

We use a union type such as string | null to indicate that a property may contain a string or null.

Q9. Why should we check response.ok when using fetch?

Because fetch generally resolves even when the server returns HTTP error statuses such as 404 or 500. Checking response.ok allows us to handle these responses explicitly.

Q10. What is a discriminated union in API state management?

It is a TypeScript union in which each state has a common identifying property, such as status. It helps represent loading, success, and error states safely.

14. Key Takeaways

  • Use interfaces or type aliases to describe API response structures.
  • Use Promise<T> to type asynchronous API functions.
  • Use generics to create reusable API functions and response structures.
  • Use unknown for unvalidated external data.
  • TypeScript assertions do not validate API responses at runtime.
  • Use Zod or another validation library when runtime validation is required.
  • Handle loading, success, and error states properly.
  • Always check HTTP response status when using fetch.

Remember: TypeScript tells us what data our application expects. Runtime validation helps verify that the API actually sends that data.

🔙
How to Use Generics in React Components :👈 👉:How to Create Type-Safe Reusable Form Components

Comments and Discussion