javascriptreactjstypescripttypesaxios

Axios typescript customize AxiosRequestConfig


I am 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 resulting 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>

I don't wanna use the old method like .d.ts.


Solution

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

    So this should do the job:

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