Typescript errors when referencing files with similar module names

倾然丶 夕夏残阳落幕 提交于 2019-12-13 07:26:16

问题


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?


回答1:


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
    {

    }
}


来源:https://stackoverflow.com/questions/36249838/typescript-errors-when-referencing-files-with-similar-module-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!