Nicky Nicky - 1 year ago 308
TypeScript Question

TypeScript: How to import a class from a submodule?

I have a TypeScript app using both

files. References are made using the triple slash notation
/// <reference path=...>
. My app has the following definition file:

declare module APP {

class Bootstrap {


I then declare a module named
so I can import it in other files:

declare module "app" {
export = APP;

Assuming my
class exists, I then import the
class using:

import { Bootstrap } from 'app';

This works.

Now I create a submodule on
, like so:

declare module APP.Service {
class Async {

I make another declaration for the submodule:

declare module "app/service" {
export = APP.Service;

Now, when I import the class
like so:

import { Async } from 'app/service';

I get the following error message:

Module '"app/service"' resolves to a non-module entity and cannot be imported using this construct.``

How do I be import a class from a submodule?


I have found a workaround by declaring a global

declare var APP_SERVICE: APP.Service.IService; // IService exists

And exporting that on my module:

declare module "app/service" {
export = APP_SERVICE;

The downside of this is that my global namespace get's polluted with
's I don't use, because I will use
, not

Answer Source

If you care about creating a nice, reusable, maintainable declaration file for a module, the preferred way is by using typings, as it handles aspects such as type dependency management and submodules very well for you.

  1. Create a separate repository for the typings your are writing.
  2. Add typings.json file with the name and path to your main typings. eg:

      "name": "my-main-module",
      "main": "index.d.ts"
  3. Add your the type declarations for your main module to index.d.ts and the type declarations for submodules to submodule-name.d.ts.


    export interface submoduleInterface {
      someProp: number


    import * as submodule from './submodule'
    export interface mainInterface {
      someProp: number
  4. Run typings bundle index.d.ts -o bundle.d.ts. This will bundle all your typings into one type declaration file, declaring the proper submodules and respecting all the necessary dependencies between modules, submodules and even external modules.

  5. Either copy this file to a custom-typings directory in your original project, or submit this repo to the typings registry so other people can also profit from it

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download