TypeScript:使用 class 作为模块

TypeScript: use class as module

无法像这样添加 class 本地接口和类型声明:

class Foo {
  interface Bar {}
  private bar: Bar;
}

到目前为止,我一直把所有东西都放在一个模块中:

module Foo {
  export interface Bar {}
  export class Foo {
    private bar: Bar;
  }
}

不过,我最近发现您可以创建 class/module "hybrids" 可以这么说。

class Foo {
  private bar: Foo.Bar;
}

module Foo {
  export interface Bar {}
}

编译器不会对此抱怨,类型检查器似乎做的一切都是正确的。这是一个坏主意吗?以后会坏吗?

文档中概述了此语言功能:

Declaration Merging: Merging Modules with Classes, Functions, and Enums

考虑到文档中对此进行了概述,并且这种模式相当普遍(尤其是在现有 JavaScript 库中),我认为可以肯定地说这种语言功能将保留下来。

这是一个名为 "Declaration Merging" 的 well-documented 功能,因此预计可以稳定运行一段时间。

具体来说,模块中任何可以生成代码的内容都将简单地成为 class 的静态成员,并且接口无论如何都不会生成代码,因此它们是否存在于 classes 中并不重要.