TypeScript:使用 jQuery 调用 AJAX 的类型提示成功数据

TypeScript: Type hint success data of AJAX call with jQuery

我们使用 TypeScript 来键入提示我们的 JavaScript 代码。我们还对 Ajax 调用使用类型提示,以定义响应数据的格式(在 success 回调中)。这就是它的样子:

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) {
            // In here, the IDE will know the structure of `response`
        }
    });
}

以上操作效果很好。在 success 函数中,我们受益于自动完成等,因为我们确实输入了提示 AjaxResponseInterface.

然而,我们也可以在我们的代码中传递承诺并调用 done 函数而不是 success:

let promise = ajax(123);

promise.done(function (response) {
    // In here, the IDE won't know that the response is of type `AjaxResponseInterface`, unless of course we type hint it again above
});

我们如何修改函数ajax的return类型,以便TypeScript知道response对象在success?

例如像这样:

function ajax(element_id:number):JQueryPromise<AjaxResponseInterface>

目标是我们可以传递 promise 对象,当我们对其调用 promise.done(function (response) {}) 时,TypeScript 知道响应的类型是 AjaxResponseInterface.

原来我们一直都有:

function ajax(element_id:number):JQueryPromise<AjaxResponseInterface>确实是解决方案。

只是我的 IDE 在 response. 上按 Ctrl+Space 时不会自动完成。但是,当尝试访问 response 上未在 AjaxResponseInterface 中定义的 属性 时,TypeScript 会报错。