Why is it impossible to export an instance of a class in TypeScript?

I have not found a way to export an instance of a class easily in TypeScript. I had to come up with the following workaround for creating the correct javascript code.

var expo = new Logger("default"); export = expo; 

generates

 var expo = new Logger("default"); module.exports = expo; 

Is there an easier way to achieve this?

+8
javascript typescript
source share
4 answers

I had to come up with the following workaround for creating the correct javascript code

Not a workaround. This is the standard way in TS.

+5
source share

Quite by accident, I found a way to export the instance:

 class MyClass(){} export default new MyClass(); 
+14
source share

One approach is to create a static instance inside the class:

 export class MyClass { static instanceOfMyClass = new MyClass(); } .. var instanceOfMyClass = MyClass.instanceOfMyClass; 
0
source share

The https://k94n.com/es6-modules-single-instance-pattern is an additional way:

 export let expo = new Logger("default"); 

Which has the advantage that you can export multiple instances of the class to a * .ts file.

0
source share

All Articles