pllee pllee - 3 months ago 7
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'
any


and


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


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');

window.alert(greeter.greetName('Name'));


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

Answer

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 () {
    alert('Stop');
}
var stage2 = <IMyInterface> <any> example; // A bit gnarly
stage2.stop();
Comments