Getter / setter on a module in TypeScript

I use AMD modules (compiler flag "-module amd") in my TypeScript project. Although I can easily use getters / setters on my classes. I would like to do the same on my modules, but

export get abc() : string { return "abc"; } 

returns

error TS1008: Unexpected token; 'module, class, interface, enumeration, import or statement ".

and

 export function get abc() : string { return "abc"; } 

returns

error TS1005: '(' expected.

What am I doing wrong?

+5
source share
3 answers

At the moment, you can add getters and setters to the class.

TypeScript uses code conversion on getters and setters to add a property to the object prototype, which is more important for classes than for modules.

+7
source

This is possible using the special export = ... syntax as follows:

 class MyModule { get abc() { return "abc"; } } var myModule = new MyModule(); export = myModule; 

This makes the instance of the MyModule class valid as a module API. You do not need to put any data in the class - just move your functions to it and otherwise leave them unchanged. The disadvantage is that if function a calls function b , it will have to say this.b() or myModule.b() (the latter is closer to the normal module export).

Also you need to declare a named variable first. You cannot just say:

 export = new MyModule(); // This doesn't work 
+4
source

For future reference only ...

Similar to what @Daniel Earwicker said and explained what @ billc.cn said, you can also create a class with a namespace and then just define getter / setter as a static method:

 export class X { static get abc():string { return "abc"; } } export namespace X { // ... other code } 

But this means that you will have a namespace in your library (module), and if you do not want to change the way you address the attributes of your library, you will need to do hack export = X; mentioned by @Daniel Earwicker.

https://www.typescriptlang.org/docs/handbook/declaration-merging.html

0
source

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


All Articles