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?

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

  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