Axios typescript customize AxiosRequestConfig

im using React and axios, recently i have created a custom config on axios like this:

import $axios from 'helpers/axiosInstance'
$axios.get('/customers', { handlerEnabled: false })

but the result ts compilation:

Argument of type ‘{ handlerEnabled: boolean; }’ is not assignable to parameter of type ‘AxiosRequestConfig’.
Object literal may only specify known properties, and ‘handlerEnabled’ does not exist in type ‘AxiosRequestConfig’.

how can i assign new types on AxiosRequestConfig?
something like this axios<AxiosRequestConfig & newType>

dont wanna use old method like .d.ts

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You can extend any library types, by using the typescript decleration merging feature. (docs)

So this should do the job:

// theFileYouDeclaredTheCustomConfigIn.ts
declare module 'axios' {
  export interface AxiosRequestConfig {
    handlerEnabled: boolean;
  }
}

Solution 2

// in axios.d.ts
import 'axios';

declare module 'axios' {   
    export interface AxiosRequestConfig {
        handlerEnabled?: boolean;   
    } 
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply