How to export a class instance in Typescript

mindparse picture mindparse · Jan 24, 2019 · Viewed 28.6k times · Source

Im authoring a TS library, and would like to export an instance of a class, I intend for it be used as singleton in the consuming application.

Right now I have the following structure:

index.ts

export { Foo } from './my-class';

foo.ts

export class Foo {
  functionA() {}
}

I'm then building into UMD format using webpack and babel, and in another application (Angular), I am able to import in my class, instantiate it and use it accordingly.

import { Foo } from 'foo';

private foo = new Foo();

const x = foo.functionA();

Is there a way to return an instantiated instance of my class or am I thinking about this the wrong way?

So instead of having to do new Foo(), the imported Foo would actually already be an instance?

Thanks

UPDATE I should have mentioned, I am exporting other things such as interfaces, so I don't think a default class export would be the right way to go correct? - see here

Answer

user310988 picture user310988 · Jan 24, 2019

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