I have the class
MyStore
that contains data and state for my JS-application. I want to receive a single instance when importing that class in other files (I am using commonjs a.k.a external modules).
Example:
MyStore.ts
class MyStore extends BaseStore {
private _items;
getItems() { return _items; }
}
export = MyStore;
OtherFile.ts:
import MyStore = require('./MyStore');
MyStore.getItems();
this doesn't work as I have to insantiate MyStore in Otherfile.ts
My current solution is to have a static singleton method:
MyStore.ts:
private static _instance = new MyStore();
static getInstance(){ return this._instance;}
OtherFile.ts
import MyStore = require('./MyStore');
MyStore.getInstance().getItems();
Is there any better way?
Edit: The reason it is a Typescript class is to allow inheritance (extending baseclass)
Use named exports to export multiple classes in TypeScript, e.g. export class A {} and export class B {} . The exported classes can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a file.
The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum. When exporting a module using export = , TypeScript-specific import module = require("module") must be used to import the module.
To export a constant in TypeScript, we can use the export keyword. export const adminUser = { //... }; to export the adminUser constant.
This should be simple, right?
class MyStore { ... }
// export a single instance
export = new MyStore(...);
Unfortunately, typescript 1.0 doesn't allow this. The type of exported values must also be exported from the module. In this case, that defeats the entire point of singletons.
The 1.1 compiler (not officially released yet, but available on GitHub) fixes this.
In the meantime, the workaround is to use declaration merging to export both an interface and an implementation with the same name:
class MyStoreImpl implements MyStore {
private _items;
getItems() { return this._items; }
}
interface MyStore {
getItems();
}
var MyStore:MyStore = new MyStoreImpl();
export = MyStore;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With