Extend AxiosRequestConfig in TypeScript

· 1 min read · 175 Words · -Views -Comments

Background

Some web requests are slow or require a global loading mask to prevent user interaction. We wanted to add a loading flag to Axios config so that when loading: true, the UI shows an indicator for the duration of the request.

Implementing the behavior is easy, but keeping type safety is trickier because AxiosRequestConfig doesn’t expose generics for arbitrary properties. The solution: declaration merging.

Code

Create a .d.ts file and merge the interface:

declare module 'axios' {
  export interface AxiosRequestConfig {
    /**
     * Show a loading spinner while the request is in flight.
     */
    loading?: boolean;
  }
}

Now editors provide proper hints where loading is used.

intellisense screenshot

Declaration Merging

Interfaces with the same name merge their members. Official docs: https://www.typescriptlang.org/docs/handbook/declaration-merging.html#merging-namespaces

Example:

interface A {
  name: string;
}
interface A {
  address: string;
}

const user: A = {
  name: 'aaa',
  address: 'bbb'
};

Final Thoughts

  1. Declaration merging keeps the customization type-safe. You could cast (as unknown as AxiosRequestConfig) or wrap Axios, but merging is cleaner.
  2. Remember: TypeScript augments JavaScript types—it doesn’t change runtime behavior.
Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover