Extending Array in TypeScript

declare global seems to be the ticket as of TypeScript 2.1. Note that Array.prototype is of type any[], so if you want to have your function implementation checked for consistency, best to add a generic type parameter yourself.

declare global {
  interface Array<T> {
    remove(elem: T): Array<T>;
  }
}

if (!Array.prototype.remove) {
  Array.prototype.remove = function<T>(this: T[], elem: T): T[] {
    return this.filter(e => e !== elem);
  }
}

You can use the prototype to extend Array:

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

Array.prototype.remove = function (o) {
    // code to remove "o"
    return this;
}

If you are within a module, you will need to make it clear that you are referring to the global Array<T>, not creating a local Array<T> interface within your module:

declare global {
    interface Array<T> {
        remove(o: T): Array<T>;
    }
}

Adding to Rikki Gibson's answer,

export{}
declare global {
    interface Array<T> {
        remove(elem: T): Array<T>;
    }
}

if (!Array.prototype.remove) {
  Array.prototype.remove = function<T>(elem: T): T[] {
      return this.filter(e => e !== elem);
  }
}

Without the export{} TS error "Augmentations for the global scope can only be directly nested in external modules or ambient module declarations."

Tags:

Typescript