A simple extension method in TypeScript

I am trying to create an extension method for a class, but it seems that something is wrong. Below is the code, the output JS file is correct, but the compiler shows the error "test.ts (10,16) twice : the close property does not exist by the value of the type" Test "" What needs to be fixed?

class Test { } interface Test { close():any; } Test.prototype.close = function() {} var t = new Test(); t.close(); 

Update : The above code is fully compiled with built-in types. I need to expand my classes.

Update 2 : problem with the old version of the compiler. Everything is fine now!

+4
source share
1 answer

This example uses inheritance to extend the original object. Naming is just for illustration.

 class Test { baseMethod() { } } class TestWithClose extends Test { close() { } } var t = new TestWithClose(); t.close(); t.baseMethod(); 

Update

You mentioned in your comment that you can write extension methods for inline functions the way you want, and I see that you want to do the same for your own code, but that is not possible.

Hope this explains why.

When creating an ad in TypeScript, you can expand that ad by adding it. You can use the declare keyword or put the file in a .d.ts file:

For example, if you have this declaration in a single file:

 declare interface ExampleInterface { methodOne(); } 

You can expand the declaration in another file:

 declare interface ExampleInterface { methodTwo(); } 

So, when you use it, you have both functions:

 function example(example: ExampleInterface) { example.methodOne(); example.methodTwo(); } 

Actually, these are not extension methods - it just tells the compiler about the implementation several times. This is especially useful for jQuery because it allows each plugin to have a definition that adds to the JQuery interface.

You cannot do this for your own TypeScript code, because adding to the interface will cause all implementations to require updates according to the interface definition.

The mental shift here is that TypeScript gives you static typing, and you are looking for dynamic behavior - so you need to choose one or the other. For example, you can simply use the dynamic behavior in which you really want it, and leave everything else statically typed:

 class Test { } // statically typed var stTest = new Test(); // dynamically typed var testExtender: any = Test; testExtender.prototype.close = function() { alert('Close'); }; var t: any = new Test(); t.close(); 

This does not mean that in the future the language will not be added to the language to support extension methods.

+4
source

Source: https://habr.com/ru/post/1444060/


All Articles