Search code examples
classtypescripttypesdependency-injectioninversion-of-control

TypeScript Types without importing classes?


I'm about to try implementing some IoC/DI framework in our application (thinking of Inversify, if there are any other recommendations) but we still have the problem of having to include the files for their Types. How do we get around this? We're using the latest version of TypeScript (2.3 as of writing this).

We have a lot of imports for various types, for example:

// Components
import {GuideTime} from '../components/guide-time/guide-time.component';
import {GuideNetwork} from '../components/guide-network/guide-network.component';
import {GuideDetail} from '../components/guide-detail/guide-detail.component';
import {Player} from '../components/player/player.component';

// Services
import {Keys, KeyService} from '../core/services/key.service';
import {GuideService} from '../core/services/guide/guide.service';
import {afterCSSUpdate} from '../core/services/utility.service';
import {DataService} from '../core/services/data/data.service';

Or just to get the type of something:

import {ITitle} from '../../models/title.interface';
import {IGuide} from '../../models/guide.interface';

Is there a way to consolidate these (preferably automatically, or globally)? I realize I can probably make a mytypes.ts file somewhere and then just import and export all the types from our application so there's a single, central file to import, but that introduces other problems (and a lot of work).

Thanks!


Solution

  • To make all of these global you would need to import them all to a single interface, and then import that interface wherever you need access to every type. Something similar to

    import * as mainInterface from 'MainInterface'
    

    Additionally, you could try importing for side effects only (which would give you access to the types), although this is not recommended in practice.

    From the documentation:

    Though not recommended practice, some modules set up some global state that can be used by other modules. These modules may not have any exports, or the consumer is not interested in any of their exports. To import these modules, use: import "./my-module.js";

    EDIT Additionally, similar to the above single interface solution, you can put each of the types into the same namespace. You can spread a namespace across multiple files using this approach, which means you can just wrap each type in a main namespace.

    namespace MainNamespace {
    
        export class GuideTime {
            ...
            }
        ...
    }