Typescript – How to change type of axios response when modified interceptor to return config.data

Here is the code

const fetcher = Axios.create()

fetcher.interceptors.response.use(config=>{
  return config.data
})

Problem is

Type of fetcher.get('...') is AxiosInstance, but it’s actually AxiosInstance.data type

So how could I change the type correctly?

24 thoughts on “Typescript – How to change type of axios response when modified interceptor to return config.data”

    1. Write the types somewhere, e.g. src/types/axios/axios.d.ts.
    import axios from 'axios'
    
    declare module 'axios' {
      export interface AxiosInstance {
        request<T = any> (config: AxiosRequestConfig): Promise<T>;
        get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
        delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
        head<T = any>(url: string, config?: AxiosRequestConfig): Promise<T>;
        post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
        put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
        patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T>;
      }
    }
    
    1. Update your tsconfig.json, e.g.
    {
      "compilerOptions": {
        "typeRoots": [
            "./node_modules/@types",
            "./src/types/",
        ]
      }
    }
    
    1. Now you can use fetcher.get<DataType>('...') and you should get the response of a type mentioned.

    This solution may work! Also review the this thread to learn more!
    Solution Ref

    Reply
  1. It is not necessary to redefine the module.

    Assuming your interceptor does response => response.data and a server response like:

    {
      book: { id: 42 }
    }
    

    This should be enough:

    type Book = {
        id: number
    }
    
    type ResponseContainer = {
        book: Book
    }
    
    request.post<Book, ResponseContainer>('/api')
        .then(({ book }) => console.log(book.id))
    
    Reply

Leave a Comment