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

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");
log.message("hello");

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

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

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) ABC.ping(x – 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.

Leave a Comment