pllee pllee - 1 year ago 55
TypeScript Question

Is there a way to add methods on the fly to a class using typescript?

I am trying create some kind of mixin method that add methods to the prototype/class on the fly but I get errors such as

The property 'greetName' does not exist on value of type 'Greeter'


The property 'greetName' does not exist on value of type 'Greeter'

when I run the following code.

class Greeter {
greeting: string;
constructor (message: string) {
this.greeting = message;
greet() {
return "Hello, " + this.greeting;

Greeter.prototype.greetName = function(name){
return this.greet() + ' ' + name;

var greeter = new Greeter('Mr');


It actually compiles to valid js and runs as expected. Is there a way to do this with out compiler warnings/errors?

Answer Source

This solution has the benefit of giving you type checking when you dynamically add a method:

class MyClass {
    start() {

var example = new MyClass();
//example.stop(); not allowed

interface IMyInterface {
    start(): void;
    stop(): void;
MyClass.prototype['stop'] = function () {
var stage2 = <IMyInterface> <any> example; // A bit gnarly