Deniss B. Deniss B. - 10 days ago 7x
TypeScript Question

How can I export multiple object instances in TypeScript?

I am building a library in TypeScript that is using a dependency injection system (inversifyJS) to construct itself and resolve dependencies internally.
The problem I have is - I want to expose multiple instances from the injection system to the consumers of the library.

Currently what I am trying to do is:

import kernel from "./src/inversify.config";
import EntityManager from './src/manager/entityManager.service';
import StorageService from './src/storage/storage.service';
import LanguageService from './src/language/language.service';

export { kernel.get<EntityManager>(EntityManager) as EntityManagerInstance };
export { kernel.get<EntityManager>(LanguageService) as LanguageServiceInstance };
export { kernel.get<EntityManager>(StorageService) as StorageServiceInstance };

A solution that I see is possible is to use a facade to export types and access them later:

import EntityManager from './src/manager/entityManager.service';
import StorageService from './src/storage/storage.service';
import LanguageService from './src/language/language.service';
import InjectionFacade from './utils/injection.facede';

export { EntityManager, LanguageService, StorageService, InjectiorFacade };
// Usage:
// import {InjectionFacade, StorageService} from 'entity-manager';
// let injectionFacade: InjectionFacade = InjectionFacade.createAndResolve();
// let storageService: StorageService = injectionFacade.getStorageService();

But the problem with this is I have one more useless abstraction

Is there a way to implement this kind of solution without loosing type definitions and exporting ready-to-use objects?


You'd want to use a multiple-declaration variable, e.g.

export const
    EntityManagerInstance = kernel.get<EntityManager>(EntityManager),
    LanguageServiceInstance = kernel.get<EntityManager>(LanguageService),
    StorageServiceInstance = kernel.get<EntityManager>(StorageService);