getter/setter on a module in TypeScript

You can only add getters and setters to a class at the moment.

The code transformation TypeScript uses on getters and setters adds the property to the prototype of the object, which makes more sense for classes than for modules.


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

class MyModule {
    get abc() {
        return "abc";
    }
}

var myModule = new MyModule();
export = myModule;

This makes an instance of the class MyModule act as the API of the module. You don't have to put any data in the class - just move your functions into it and otherwise leave them unchanged. The downside is that if function a calls function b it will have to say this.b() or myModule.b() (the latter is closer to a normal module export).

Also you have to declare a named variable first. You can't just say:

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

You can export your getter directly, via a class, like this:

// helper class to be removed when/if module-level getters are available
class _someHelper {
    static get myStaticString(): string {
        return "hi, world";
    }
}

export const myStaticString = _someHelper.myStaticString;

Then import like:

import { myStaticString } from "my-module";

Not the prettiest, but it does work.