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?
A TypeScript Interface can include method declarations using arrow functions or normal functions, it can also include properties and return types. The methods can have parameters or remain parameterless.
In TypeScript, the constructor method is always defined with the name "constructor". In the above example, the Employee class includes a constructor with the parameters empcode and name . In the constructor, members of the class can be accessed using this keyword e.g. this. empCode or this.name .
In TypeScript, we can easily extend and implement interfaces. This is not possible with types though. Interfaces in TypeScript can extend classes, this is a very awesome concept that helps a lot in a more object-oriented way of programming. We can also create classes implementing interfaces.
The newly created classes are called the child/sub classes. A class inherits from another class using the 'extends' keyword. Child classes inherit all properties and methods except private members and constructors from the parent class.
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 MyClass { stop(): void; } MyClass.prototype['stop'] = function () { alert('Stop'); } var stage2 = example; stage2.stop();
There is another way to do this.
Greeter["SomeProperty"] = function() { return "somevalue"; };
Works the same and uses the property indexer function in javascript and typescript doesn't complain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With