weixin_33725126 2016-04-22 00:15 采纳率: 0%
浏览 20

输入jQuery扩展

Someone else wrote the extension. It surfaces the ajax progress events with a syntax like this:

$.ajax(url)
  .progress(function(e) {
    // tracking downloading
  })
  .uploadProgress(function(e) {
    // tracking uploading
    // if (e.lengthComputable) {
    //  var percentage = Math.round((e.loaded * 100) / e.total);
    //  console.log(percentage);
    //}
  });

TypeScript complains that these new methods don't exist.

It seems to me that I need to somehow add them to JQueryXHR which is defined in jquery.d.ts from DefinitelyTyped. This being a third party library I don't want to edit it - that would interfere with updates.

How do I go about adding a method to a TypeScript interface that has already been defined in a file that I don't want to edit?

  • 写回答

1条回答 默认 最新

  • weixin_33713350 2016-04-22 00:33
    关注

    How do I go about adding a method to a TypeScript interface that has already been defined in a file that I don't want to edit

    TypeScript interfaces are open ended and designed to accomodate this.

    Just create a thelib.d.ts with:

    interface JQueryXHR {
      progress: any;
      uploadProgress: any;
    }
    

    More

    https://basarat.gitbooks.io/typescript/content/docs/types/ambient/interfaces.html


    Same but stronger typing

    The answer as given addresses the question as asked, and has the advantage of simplicity. But in the field you need to do better. Here it is with stronger typing. This matters if you want "fluent" eg .then().fail().done() etc.

    interface JQueryXHR {
      progress<R>(callback: (e: ProgressEvent, status: string) => R): JQueryPromise<R>;
      uploadProgress<R>(callback: (e: ProgressEvent, status: string) => R): JQueryPromise<R>;
    }
    

    You don't need a triple-slash reference. Presumably it's because JQueryPromise is in scope for the main definition of JQueryXHR.

    评论

报告相同问题?