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.
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
- Declaration merging keeps the customization type-safe. You could cast (
as unknown as AxiosRequestConfig
) or wrap Axios, but merging is cleaner. - Remember: TypeScript augments JavaScript types—it doesn’t change runtime behavior.