typescripttypescript1.7

Typescript errors when referencing files with similar module names


I have one typescript class like this;

module my.services {
   export class MyService {
      ...
   }
}

And another like this;

module com.my.component {

   import MyService = my.services.MyService;

   export class MyComponent {
      ...
   }
}

But in the 2nd class I get a Typescript error saying

Module 'com.my' has no exported member 'services'

What is the correct way to reference MyService in this case?


Solution

  • If we will take a look at what specification says about namespaces like 'A.B.C' here: namespace declarations it is easy to see why you get the error. Your 'com.my.component' namespace declaration is effectively:

    namespace com
    {
        export namespace my
        {
            export namespace component 
            {
                import MyService = my.services.MyService;
    
                export class MyComponent extends MyService
                {
    
                }
            }
        }
    }
    

    And therefore any attempt to reference anything inside 'my' declaration starting with 'my....' will attempt to search for it inside current 'com.my' namespace.

    To fix this you can move import outside 'my' namespace declaration:

    import MyService = my.services.MyService;
    
    namespace com
    {
        export namespace my
        {
            export namespace component 
            {
                export class MyComponent extends MyService
                {
    
                }
            }
        }
    }
    

    Or in shorter version:

    import MyService = my.services.MyService;
    
    module com.my.component 
    {
        export class MyComponent extends MyService
        {
    
        }
    }