引用具有相似模块名称的文件时出现 Typescript 错误

Typescript errors when referencing files with similar module names

我有一个这样的打字稿class;

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

还有一个这样的;

module com.my.component {

   import MyService = my.services.MyService;

   export class MyComponent {
      ...
   }
}

但是在第二个 class 中我收到一个 Typescript 错误说

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

在这种情况下引用 MyService 的正确方法是什么?

如果我们在此处查看有关 'A.B.C' 等名称空间的规范说明:namespace declarations 很容易看出为什么会出现错误。您的 'com.my.component' 命名空间声明实际上是:

namespace com
{
    export namespace my
    {
        export namespace component 
        {
            import MyService = my.services.MyService;

            export class MyComponent extends MyService
            {

            }
        }
    }
}

因此,任何试图引用 'my' 声明中以 'my....' 开头的任何内容的尝试都将尝试在当前 'com.my' 命名空间中搜索它。

要解决此问题,您可以将导入移到 'my' 命名空间声明之外:

import MyService = my.services.MyService;

namespace com
{
    export namespace my
    {
        export namespace component 
        {
            export class MyComponent extends MyService
            {

            }
        }
    }
}

或更短的版本:

import MyService = my.services.MyService;

module com.my.component 
{
    export class MyComponent extends MyService
    {

    }
}