Crine Crine - 3 months ago 15
TypeScript Question

Add a function to a prototype globally (from within a module)

I want to add a function to the Array prototype in Typescript (1.8) from within a module.

I am altering the prototype in my utils.ts file:

declare global {
interface Array<T> {
remove(obj: any): void;
}
}

Array.prototype.remove = function(obj) {
var idx = this.indexOf(obj);
if (idx > -1) {
this.splice(idx, 1);
}
}


And now I would like to apply that change globally in my main.ts file somehow like this:

import {Array<T>.remove} from "./utils.ts"

let arr = ["an", "array"];
arr.remove("array");


I can import the interface declaration but the change to the prototype of Array is not available in the main.ts file. How can I make a change to a prototype and apply that globally or somehow import that "remove" functionality?

Answer

This works for me:

test.ts:

export {};

declare global {
    interface Array<T> {
        remove(obj: any): void;
    }
}

Array.prototype.remove = function(obj) {
    var idx = this.indexOf(obj);
    if (idx > -1) {
        this.splice(idx, 1);
    }
}

test2.ts:

import "./test";

let arr = ["an", "array"];
arr.remove("array");
console.log(arr);

Compile and run:

tsc -m "commonjs" ./test2.ts
node ./test2.js

Output:

[ 'an' ]