打字稿:私有 class 对不同文件中同一模块中的 classes 可见

Typescript: Private class which is visible to classes in same module in different files

我的项目使用 'Multi-file internal modules' 方法。在构建期间,所有内容都被编译到一个 Javascript 文件中。

仍然困扰我的一件事是我无法找到一种方法来让 类 仍然可见和可用的私有模块级别 类(未导出到定义文件)在位于单独文件中的同一模块中(即 C# 内部 类)。有什么建议吗?

Foo.ts:

module shared {
  class Foo { 
  }
}

Bar.ts:

module shared {
  export class Bar { 
    constructor() {
      this.foo = new shared.Foo();
    }  
  }
}

Baz.ts:

module shared {
  export class Baz { 
    constructor() {
      this.foo = new shared.Foo();
    }  
  }
}

对此没有语言方面的解决方案。出现这种情况的原因有两个方面——您的代码的使用者看到了什么,以及 JavaScript 是如何发出的。

从发射端看,shared::Fooshared 对象的导出成员,或者不是。如果不导出,shared:Baz 将看不到它,也将无法使用它。因此,模块中的任何 'internal' class 显然都需要根据 emit.

导出

从消费的角度来看,这里有一个微妙的危险。假设这件事发生了:

// ** YourCode.d.ts **
declare module shared {
   class Bar { ... }
   class Baz { ... }
}

// ** SomeConsumer.ts **
// Hey, 'shared' is a good namespace!
module shared {
    // My own personal Foo
    export class Foo {
    }
}

刚刚发生了什么?您的代码的用户刚刚踩到了 shared.Foo 成员而没有意识到。一切都会在运行时中断。破坏宇宙的危险成员组是一个无证雷区。

如果您有一些成员应该在外部使用而一些成员不应该在外部使用,那么最好的解决方案是使用一个名为 InternalImplementation 的嵌套模块来提示消费者他们实际上不应该自己使用这些对象。