In our development process, we implement TypeScript for type hinting in our JavaScript code. Type hinting is utilized for Ajax calls as well to define the response data format within the success
callback. This exemplifies how it could be structured:
interface AjaxResponseInterface {
width: number;
height: number;
etc: any;
}
function ajax(element_id: number): JQueryPromise<any> {
return $.ajax({
url: '/ajax/get-details',
type: 'POST',
data: {
element_id: element_id
},
dataType: 'json',
success: function (response: AjaxResponseInterface) {
// With this setup, the IDE comprehends the structure of `response`
}
});
}
The above method functions smoothly. Within the success function, we gain from autocompletion abilities due to typing AjaxResponseInterface
.
However, we may circulate the promise across our code and utilize the done
function instead of success
:
let promise = ajax(123);
promise.done(function (response) {
// In this case, the IDE lacks knowledge that the response aligns with `AjaxResponseInterface`, unless we re-type hint it previously
});
How do we adjust the return type of the function ajax
so TypeScript identifies the type of the response
object within success
?
For instance, something akin to:
function ajax(element_id: number):JQueryPromise<AjaxResponseInterface>
The objective is to enable passing around the promise object gracefully, where upon calling
promise.done(function (response) {})
, TypeScript recognizes the response type as AjaxResponseInterface
.