axios Function Overloading
# axios Function Overloading
# Requirements Analysis
Currently, our axios function only supports passing 1 argument, as follows:
axios({
url: '/extend/post',
method: 'post',
data: {
msg: 'hi'
}
})
2
3
4
5
6
7
We want the function to also support passing 2 arguments, as follows:
axios('/extend/post', {
method: 'post',
data: {
msg: 'hello'
}
})
2
3
4
5
6
The first argument is the url, and the second argument is config. This function is somewhat similar to the argument types supported by the axios.get method, except that if we want to specify the HTTP method type, we still need to pass method in config.
This is where the function overloading concept we learned earlier comes in. Let's implement it.
# Overloading Implementation
First, we need to modify the AxiosInstance type definition.
types/index.ts:
export interface AxiosInstance extends Axios {
(config: AxiosRequestConfig): AxiosPromise
(url: string, config?: AxiosRequestConfig): AxiosPromise
}
2
3
4
5
We added a new function definition that supports 2 arguments, where url is a required parameter and config is an optional parameter.
Since the axios function actually points to the request function, let's modify the request function's implementation.
core/Axios.ts:
request(url: any, config?: any): AxiosPromise {
if (typeof url === 'string') {
if (!config) {
config = {}
}
config.url = url
} else {
config = url
}
return dispatchRequest(config)
}
2
3
4
5
6
7
8
9
10
11
We changed the request function's parameters to 2, with both url and config being any type, and config remaining optional.
In the function body, we check whether url is a string type. If it is a string type, we proceed to check config, since it might not be passed. If it's empty, we construct an empty object and then add url to config.url. If url is not a string type, it means we passed a single argument, and url is actually config, so we assign url to config.
Note that although we modified the request implementation to support 2 types of parameters, the externally provided request interface remains unchanged. Think of this as merely an internal implementation change that doesn't need to match the external interface -- it only needs to remain compatible with the interface.
# Writing the Demo
examples/extend/app.ts:
axios({
url: '/extend/post',
method: 'post',
data: {
msg: 'hi'
}
})
axios('/extend/post', {
method: 'post',
data: {
msg: 'hello'
}
})
2
3
4
5
6
7
8
9
10
11
12
13
14
We used both ways of calling axios. Open the page and run the demo. Through the network panel, we can see that both request methods are working correctly.
At this point, we have implemented function overloading for axios. The official axios supports a capability where we can define the type of the return data and specify that type when making a request, so that we can access the data type in the response data. In the next section, we will implement this feature.