FG
๐Ÿ”Œ APIs & SDKs

How to use Axios with TypeScript when using response interceptors (AxiosResponse issue)

Freshabout 20 hours ago
Mar 14, 20260 views
Confidence Score95%
95%

Problem

Summary In a project I am migrating to TypeScript (TS), I have a response interceptor `r => r.data`. How do I inform TS that I am not expecting a type of `AxiosResponse`? I've tried overriding using `as Array<...` but that doesn't work as `AxiosResponse` can't be cast as an `Array` (e.g. does not has .length). Thanks! Context - axios version: 0.16.2 - Environment: Visual Studio Code

Unverified for your environment

Select your OS to check compatibility.

1 Fix

Canonical Fix
Unverified Fix
New Fix โ€“ Awaiting Verification

Implement Type-Safe Response Interceptors with Axios in TypeScript

Medium Risk

The issue arises because TypeScript does not infer the type of the response data correctly when using response interceptors in Axios. By default, Axios returns an `AxiosResponse` type, which includes metadata about the response. To inform TypeScript about the expected data type, you need to define a generic type for Axios requests and responses.

Awaiting Verification

Be the first to verify this fix

  1. 1

    Define a Generic Type for Axios Response

    Create a generic interface that extends AxiosResponse to specify the expected data type.

    typescript
    interface ApiResponse<T> extends AxiosResponse { data: T; }
  2. 2

    Set Up Axios Instance with Generic Type

    Create an Axios instance that uses the generic type defined in the previous step. This will ensure that the response interceptor can properly infer the data type.

    typescript
    const axiosInstance = axios.create();
    
    axiosInstance.interceptors.response.use<ApiResponse<MyDataType>>(response => response.data);
  3. 3

    Use the Axios Instance in API Calls

    When making API calls, use the defined Axios instance to ensure type safety across your application.

    typescript
    const fetchData = async (): Promise<MyDataType> => {
      return await axiosInstance.get<MyDataType>('https://api.example.com/data');
    };
  4. 4

    Test the Implementation

    Run your application and ensure that the API calls return the expected data type without TypeScript errors.

    typescript
    // Example usage
    fetchData().then(data => {
      console.log(data);
    });

Validation

Confirm that the TypeScript compiler does not produce any type errors when using the response interceptor and that the API response is correctly typed. Additionally, verify that the application functions as expected with the new type-safe implementation.

Sign in to verify this fix

Environment

Submitted by

AC

Alex Chen

2450 rep

Tags

axioshttpapi