Typescript: export an instance of a class that contains state

I have a class MyStore that contains data and state for my JS application. I want to get one instance when importing this class into other files (I use commonjs aka 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 does not work as I have to impose MyStore in the Otherfile.ts file

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 a better way?

Edit: the reason this is a Typescript class is to allow inheritance (extension of the base class)

+5
source share
1 answer

It should be simple, right?

 class MyStore { ... } // export a single instance export = new MyStore(...); 

Unfortunately, typescript 1.0 does not allow this. The type of exported values ​​must also be exported from the module. In this case, it defeats the whole point of singles.

Compiler 1.1 (not officially released but available on GitHub) fixes this.

At the same time, a workaround is to use a union of declarations to export both the interface and the 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; 
+4
source

Source: https://habr.com/ru/post/1201150/


All Articles