Why is it not possible to export a class instance in TypeScript?
I had to come up with the following workaround to generate proper javascript code
Not a workaround. This is the standard way in TS to do a root level export.
Is there an easier way of achieving this
Yes. export = new Variable
. Example:
export = new Foo();
Future
For ES modules you should instead use a default
export:
export default expo = new Logger("default");
Which will in most cases have the same effect as a root level export.
On https://k94n.com/es6-modules-single-instance-pattern is an additional way of doing this:
export let expo = new Logger("default");
Which has the advatage that it is possible to export several class instances in a *.ts file.
Quite by accident, I found this way to export an instance:
class MyClass(){}
export default new MyClass();