Peter Wone Peter Wone - 7 months ago 18
Javascript Question

Typing a jQuery extension

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?

Answer

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.