0

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?

Peter Wone
  • 17,965
  • 12
  • 82
  • 134
  • I think what you're looking for is the ability to "extend" an interface in TypeScript. See if this explains that concept: https://github.com/Microsoft/TypeScript/issues/280, http://stackoverflow.com/questions/32948271/extend-interface-defined-in-d-ts-file and http://stackoverflow.com/questions/23217334/how-do-i-extend-a-typescript-class-definition-in-a-separate-definition-file – jfriend00 Apr 22 '16 at 00:21

1 Answers1

0

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.

Peter Wone
  • 17,965
  • 12
  • 82
  • 134
basarat
  • 261,912
  • 58
  • 460
  • 511
  • 1
    I solved this myself but since you wrote a correct answer while I was busy I will update your answer with a more strongly typed interface and accept it. – Peter Wone Apr 22 '16 at 00:44