15

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

Ru Chern Chong
  • 3,692
  • 13
  • 33
  • 43
Zeinab Malaki
  • 333
  • 2
  • 3
  • 7

2 Answers2

32

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;
  }
}
Eddie Cooro
  • 1,676
  • 14
  • 18
  • For me, this creates errors like "Property 'create' does not exist on type `typeof import("axios")'`. Ironically, the `import 'axios'` from the downvoted answer below seems to fix it. – Pieter Jul 11 '22 at 06:20
  • 1
    This is because in order to properly augment a module in TS, you need to import the "target" module into the context in which you're performing the augmentation. https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation – WoodyWoodsta Jun 01 '23 at 08:49
3
// in axios.d.ts
import 'axios';

declare module 'axios' {   
    export interface AxiosRequestConfig {
        handlerEnabled?: boolean;   
    } 
}
  • 1
    Please, add some explanation to your code. – Shunya Oct 21 '21 at 20:03
  • 2
    [A code-only answer is not high quality](//meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers). While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please [edit] your answer to include explanation and link to relevant documentation. – Stephen Ostermiller Oct 22 '21 at 00:10
  • Just in case someone tries to understand the answer. You should be creating another type file containing the above. If you paste it inside your *index.d.ts* where you have your typings it will break them. – kimy82 Jan 12 '22 at 11:57