typescript - TypeScript 中的内部模块和外部模块有什么区别?

标签 typescript

我花了一些时间阅读 Typescript 语言规范,对内部外部 模块之间的区别有些困惑。以下是直接取自规范的描述:

Internal modules (section 9.2.2) are local or exported members of other modules (including the global module and external modules). Internal modules are declared using ModuleDeclarations that specify their name and body. A name path with more than one identifier is equivalent to a series of nested internal module declarations.

External modules (section 9.4) are separately loaded bodies of code referenced using external module names. An external module is written as a separate source file that contains at least one import or export declaration. In addition, external modules can be declared using AmbientModuleDeclarations in the global module that directly specify the external module names as string literals. This is described further in section 0.

根据我的理解,我认为外部模块对应于 typescript 文件,不包含仅导出一组类型和/或变量的模块定义。从另一个 typescript 文件中,我可以使用 import foo = module("foo");

foo.ts 中简单地导入一个外部模块

谁能给我解释一下外部模块和内部模块的区别?

最佳答案

规范的第 9.3 和 9.4 节对此进行了更清楚的解释。我将在此处重现这些部分中给出的一些示例。

外部模块

假设以下代码在main.ts中。

import log = module("log");
log.message("hello");

此文件引用了一个外部模块 log,由 log.ts 导出的内容定义。

export function message(s: string) { 
  console.log(s); 
}

请注意 log.ts 没有在任何地方使用 module 关键字。它只是使用 export 导出内容。

内部模块

这个文件有两个内部模块,X.Y.Z

module A.B.C { 
  import XYZ = X.Y.Z; 
  export function ping(x: number) { 
    if (x > 0) XYZ.pong(x – 1); 
  }
} 
module X.Y.Z { 
  import ABC = A.B.C; 
  export function pong(x: number) { 
    if (x > 0) ABC.ping(x – 1); 
  } 
}

这些行为(大部分)类似于外部模块,但它们包含在一个文件中,您无需引用任何外部文件即可使用它们。它们在定义时必须包含在 module block 中。

关于typescript - TypeScript 中的内部模块和外部模块有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12841557/

相关文章:

html - 如果超出可见屏幕,如何找到我的下拉 div?

angular - Typescript 装饰器如何让 Angular 2 发现类型元数据

javascript - 基于输入参数的 Typescript 函数重载

reactjs - 如何使用样式组件扩展(MUI)React 组件的 TS 接口(interface)?

angular - 文件删除上传数据传输为空Angular 2

javascript - Redux 操作 typescript 返回类型不起作用

javascript - typescript :请求类型上不存在属性 'decoded'

reactjs - 如何将 TypeScript 与 withRouter、connect、React.Component 和自定义属性一起使用?

typescript - 使用 ionic 生成命令创建文件时如何更改默认选项卡缩进大小?

html - 如何在组件选择器上添加禁用属性?