2
0
mirror of https://github.com/tenrok/axios.git synced 2026-05-15 11:59:42 +03:00

typings: allow custom return types

response interceptor might change the type from AxiosResponse to anything they like
This commit is contained in:
Stephan Schneider
2018-06-14 11:56:20 +02:00
committed by Khaled Garbaya
parent 0b3db5d87a
commit 73cab975f0
2 changed files with 57 additions and 10 deletions
+50 -3
View File
@@ -103,6 +103,8 @@ interface User {
name: string;
}
// with default AxiosResponse<T> result
const handleUserResponse = (response: AxiosResponse<User>) => {
console.log(response.data.id);
console.log(response.data.name);
@@ -121,11 +123,11 @@ axios.get<User>('/user', { params: { id: 12345 } })
.catch(handleError);
axios.head<User>('/user')
.then(handleResponse)
.then(handleUserResponse)
.catch(handleError);
axios.delete<User>('/user')
.then(handleResponse)
.then(handleUserResponse)
.catch(handleError);
axios.post<User>('/user', { foo: 'bar' })
@@ -142,7 +144,52 @@ axios.put<User>('/user', { foo: 'bar' })
axios.patch<User>('/user', { foo: 'bar' })
.then(handleUserResponse)
.catch(handleError);
.catch(handleError);
// (Typed methods) with custom response type
const handleStringResponse = (response: string) => {
console.log(response)
}
axios.get<User, string>('/user?id=12345')
.then(handleStringResponse)
.catch(handleError);
axios.get<User, string>('/user', { params: { id: 12345 } })
.then(handleStringResponse)
.catch(handleError);
axios.head<User, string>('/user')
.then(handleStringResponse)
.catch(handleError);
axios.delete<User, string>('/user')
.then(handleStringResponse)
.catch(handleError);
axios.post<User, string>('/user', { foo: 'bar' })
.then(handleStringResponse)
.catch(handleError);
axios.post<User, string>('/user', { foo: 'bar' }, { headers: { 'X-FOO': 'bar' } })
.then(handleStringResponse)
.catch(handleError);
axios.put<User, string>('/user', { foo: 'bar' })
.then(handleStringResponse)
.catch(handleError);
axios.patch<User, string>('/user', { foo: 'bar' })
.then(handleStringResponse)
.catch(handleError);
axios.request<User, string>({
method: 'get',
url: '/user?id=12345'
})
.then(handleStringResponse)
.catch(handleError);
// Instances