Extending functionality in TypeScript [duplicate]

I have found the solution. It takes a combination of the interface and the JavaScript implementation. The interface provides the contract for TypeScript, allowing visibility of the new method. The JavaScript implementation provides the code that will be executed when the method is called.

Example:

interface String {
    foo(): number;
}

String.prototype.foo= function() {
    return 0;
}

As of TypeScript 1.4 you can now also extend static members:

interface StringConstructor {
    bar(msg: string): void;
}

String.bar = function(msg: string) {
    console.log("Example of static extension: " + msg);
}

Leave a Comment