Typically, Typescript modules are declared like
declare module MyModule {
....
}
but sometimes I also see it like
declare
As outlined in the Typescript docs, there is a difference between the two styles. module x {
is equivalent to namespace x {
, while module "x" {
is unlike either of the other two. This is definitely confusing, which is why the documentation using the latter syntax in all cases.
The question then must be asked, what is the difference between a namepsace and a so-called external module (i.e., a module that is declared with quotes)?
We get some insight from the docs:
Just like namespaces, modules can contain both code and declarations. The main difference is that modules declare their dependencies.
Modules also have a dependency on a module loader (such as CommonJs/Require.js).
Essentially, using the quotes indicates that it is indeed a module in the traditional Javascript sense that requires explicit import to be used. Without the quotes, you just create a global object that can be referenced and utilized without any explicit require
s.
"Internal modules" === “namespaces”
“External modules” === “modules”
A note about terminology: It’s important to note that in TypeScript 1.5, the nomenclature has changed. “Internal modules” are now “namespaces”. “External modules” are now simply “modules”, as to align with ECMAScript 2015’s terminology, (namely that module X { is equivalent to the now-preferred namespace X {).
/*
Note: All of these files in the same folder, i.e. the same path!
*/
// declare a namespace, demoNamespace.d.ts
declare namespace "DemoNamespace" {
export function fn(): string;
}
// using a namespace, demoNamespaceModule.ts
import * as n from "demoNamespace";
//let f = new n.DemoNamespace.fn(); ???
// export a module, demoModule.ts
export class Alpha { /* ... */ }
export class Beta { /* ... */ }
// using a module, demoModuleTest.ts
import * as m from "./demoModule";
let a = new m.Alpha();
let b = new m.Beta();
namespaces-and-modules namespaces modules