9

I didn't find a way to export a class instance easily in TypeScript. I had to come up with the following workaround to generate proper javascript code.

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

generates

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

Is there an easier way of achieving this?

3
  • It exists something, you should read [Why does Typescript use the keyword “export” to make classes and interfaces public?][1] [1]: stackoverflow.com/questions/15760462/… Commented Apr 8, 2015 at 20:39
  • 3
    What code were you trying to write? It seems like you've accomplished your goal? Commented Apr 8, 2015 at 21:11
  • I wanted to write export new Logger("default");. Hm... still don't find it very clear. Anyway, thanks. Commented Apr 9, 2015 at 16:01

4 Answers 4

20

Quite by accident, I found this way to export an instance:

class MyClass(){}

export default new MyClass();
Sign up to request clarification or add additional context in comments.

Comments

5

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.

2 Comments

Added a Yes / No answer. I don't see it answered in any of the other answers on the page.
Good on you for improving this 3 years after the fact (not sarcasm)!
5

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.

Comments

0

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

export class MyClass {
  static instanceOfMyClass = new MyClass();
} 

..

var instanceOfMyClass = MyClass.instanceOfMyClass;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.