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

Viewed 5566

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?

3 Answers

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<unknown, ResponseContainer>('/api')
    .then(({ book }) => console.log(book.id))
  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

You can try this one as in this

fetcher.get<DataType>('...')

EX: if it's returning a number

fetcher.get<number>('...')
Related