Extend AxiosRequestConfig in TypeScript

Use declaration merging to add custom properties (e.g., loading flags) to AxiosRequestConfig without sacrificing type safety.

Jan 11, 2021 · 1 min read · 175 Words · -Views -Comments · Programming
TypeScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

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