Mauro Valvano
Mauro Valvano

Reputation: 933

What is the difference between namespaces and modules in typescript

I've used typescript from some months now and i have not understand the difference from namespaces and modules yet.

I know that before they were named internal and external modules, but with both i can import classes from other files. So what is the real difference?

Upvotes: 21

Views: 7205

Answers (2)

As it is stated in the TS-handbook there are 2 kind of modules: "internal" & "external". The code in the internal module is written in Typescript and the "external" is written in Javascript.

In order to align with new ECMAScript 2015's terminology they decided to rename them as follows:

  1. "Internal modules" are now "namespaces".
  2. "External modules" are now simply "modules", as to align with ECMAScript

So:

  • The way you write your code is different
  • When using modules the classes are not exposed in the global scope, while using namespaces:

Example:

Let's say you have public namespace sequence NamespaceA.NamespaceB.NamespaceC which exposes public class ClassD. You can access all of these globally this way:

window.NamespaceA
window.NamespaceA.NamespaceB
window.NamespaceA.NamespaceB.NamespaceC
window.NamespaceA.NamespaceB.NamespaceC.ClassD

without saying window.NamespaceA = NamespaceA

and if you use modules you have to use the "magic" above

Upvotes: 7

toskv
toskv

Reputation: 31600

Namespaces are TypeScript's way of structuring code when you don't want the outputed Javascript code to use a module loader.

You can find more about namespaces vs modules in the handbook here.

Upvotes: 3

Related Questions