Valentin Valentin - 25 days ago 4x
TypeScript Question

What's the difference between internal and external modules in TypeScript?

I have spent some time reading the Typescript language specification and am somewhat confused about the difference between internal and external modules. Here is the description taken directly from the specification:

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.

From what I've understood I think that external modules correspond to typescript files without enclosing module definitions that simply export a set of types and/or variables. From another typescript file I can simple import an external module in foo.ts with `import foo = module("foo");

Can somebody explain to me the destinction between external and internal modules?


Sections 9.3 and 9.4 of the specification explain this more clearly. I'll reproduce here some of the examples given in those sections.

External modules

Suppose the following code is in main.ts.

import log = module("log");

This file references an external module log, defined by whatever log.ts exports.

export function message(s: string) { 

Notice that log.ts doesn't use the module keyword anywhere. It just exports things with export.

Internal modules

This file has two internal modules, 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) – 1); 

These behave (mostly) like external modules, but they are contained in one file and you don't have to reference any outside files to use them. They have to be contained inside of a module block when they are defined.