Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 659
pllee Avatar asked Oct 02 '12 21:10

pllee


People also ask

Can TypeScript interface have methods?

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.

How do you define a method of a class in TypeScript?

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 .

Can class implement type TypeScript?

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.

What TypeScript keyword is used to make a class available to another class?

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.


2 Answers

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(); 
like image 123
Fenton Avatar answered Sep 16 '22 15:09

Fenton


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.

like image 20
James Hancock Avatar answered Sep 18 '22 15:09

James Hancock