Add a method to an existing class in typescript?

The "Declaration Merging > Module Augmentation" section from the TypeScript docs seems to offer the solution:

https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation

In your case, if class A is exported from file1.ts, and you want to add methodY() to that class within a different module file2.ts, then try this:

//// file1.ts
export class A extends B {
    constructor(...);
    methodX(): void;
}

//// file2.ts
import { A } from "./file1";
declare module "./file1" {
    interface A {
        methodY(): void;
    }
}
A.prototype.methodY = function() {}

You could do it by making an interface with the new method and modifying the prototype.

Something like this:

class B { }

class A extends B {
    constructor() {
        super();
    }
    methodX(): void { };
    methodY(): void { };
}


interface B {
    newMethod(): void;
}

B.prototype.newMethod = function () { console.log('a') };

This allows you do have proper typing when doing.

new A().newMethod();

I made a playground example here.


You can do it directly as A.prototype.functionName = function(){...}

Here is a plunker: http://plnkr.co/edit/6KrhTCLTHw9wjMTSI7NH?p=preview