Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: Export instance of class that holds state

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)

like image 573
Anders Avatar asked Aug 26 '14 12:08

Anders


People also ask

How do I export a class instance in TypeScript?

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.

What is export {} in TypeScript?

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.

How do I export a TypeScript Const?

To export a constant in TypeScript, we can use the export keyword. export const adminUser = { //... }; to export the adminUser constant.


1 Answers

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;
like image 161
Gjorgi Kjosev Avatar answered Nov 03 '22 02:11

Gjorgi Kjosev