Search code examples
javascripttypescripttypescript-typingspolyfillstsc

How to inform TypeScript compiler of extensions to JS Array prototype?


I have created a polyfill for the JavaScript Array;

if (Array.prototype.remove !== 'function') {
    Array.prototype.remove = function (value) {
        var idx = this.indexOf(value);
        if (idx !== -1) {
            return this.splice(idx, 1);
        }
        return false;
    };
}

Now I am upgrading the original JavaScript project to a TypeScript project and the tsc complains about the usage of the .remove method:

class Archive {
   documents: DocInfo[] = [];  // <-- Array of class DocInfo

   addDocument(document: DocInfo) {
      ...
   }

   deleteDocument(document: DocInfo) {
      this.documents.remove(document);
                     ^^^^^^
                     tsc complains here: TS2339:Property 'remove' does not exist on type 'DocInfo[]'
   }
}

How can I tell the tsc about this extension?

I tried creating a typings file, but without any success:

declare module 'Array' {
    export function removeByAttr(propertyName: string, propertyValue: any);
}

Thanks


Solution

  • The typings should extend Array<T> interface:

    interface Array<T> {
        remove(item: T): boolean;
    }