How to export a class instance in Typescript

If you want singleton only, you should stick to the singleton convention,

  export class Foo {
    private static _instance = new Foo();
    private constructor() {

    }

    static get instance() {
      return this._instance;
    }

  }

  export const foo = Foo.instance;

You can control what you're returning like so:

// Export the named class directly
export class Foo { }

// Export the named class indirectly
class Bar { }
export { Bar }

// Export an instance of the class directly
export const foo = new Foo();

// Export an instance of the class indirectly
const bar = new Bar();
export { bar };

Here's a TypeScript Playground link showing the code compiles and the produced javascript.

The TypeScript Handbook official documentation for exports (and imports, and re-exports): https://www.typescriptlang.org/docs/handbook/modules.html#export

The MDN documentation (courtesy of jo_va): https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

And here's Basarat's guide for them: https://basarat.gitbooks.io/typescript/docs/project/modules.html


It is possible to export the instance of the class Members.

Export the class instance like this: export const playerRoutes = new Routes

Export the class like this: export class player


Yes this is totally possible, and this is a standard way to do it in TS too.

export default new Foo();

If however you want to import not only this instance but interfaces as well, you would export the singleton like this:

export const foo = new Foo();

You can find the export doc here