TypeScriptを使用してJavaScriptコードを入力します。また、レスポンスデータの形式を定義するために、Ajax呼び出しにタイプヒントを使用します(success
コールバック内)。これは次のようになります。TypeScript:jQueryを使用したAJAX呼び出しのヒント成功データ
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`
}
});
}
上記の作業は問題ありません。成功関数内でヒントAjaxResponseInterface
を入力したので、自動補完などのメリットがあります。
しかし、我々はまた、私たちのコード内の周りの約束を渡して、代わりにsuccess
のdone
機能を呼び出すことができます:活字体は何を知っているように、
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
の戻り値の型を変更することができますタイプ:response
オブジェクトはsuccess
ですか?
など。このような何か:
function ajax(element_id:number):JQueryPromise<AjaxResponseInterface>
目標は、私たちは周りの約束オブジェクトを渡すことができますし、我々はそれにpromise.done(function (response) {})
を呼び出すときに、活字体が応答がタイプAjaxResponseInterface
であることを知っているということです。
'...'の代わりに 'JQueryPromise 'を使うだけです。 –
Bergi
また、この関数自体が応答で面白いことをしない場合、 'success'関数を持つ必要はありません。また、この関数のすべての使用法が応答を少し変換する必要があることが判明した場合は、 '.then(response =>)'関数の結果を返すことで自分自身で行うことができます。 –
Katana314
@ Katana314私たちが達成しようとしていることを示すために 'success'コールバックを追加しました。 – Lionel