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?
In Python-speak, modules are a namespace—a place where names are created. And names that live in a module are called its attributes. Technically, modules correspond to files, and Python creates a module object to contain all the names defined in the file; but in simple terms, modules are just namespaces.
The namespace is used for logical grouping of functionalities. A namespace can include interfaces, classes, functions and variables to support a single or a group of related functionalities. A namespace can be created using the namespace keyword followed by the namespace name.
In TypeScript, a module is a file containing values, functions, or classes. You can make some of them public, i.e. visible from other modules, by exporting them. Non exported objects are private.
TypeScript is an extension of the JavaScript language that uses JavaScript's runtime with a compile-time type checker. In TypeScript, you can use namespaces to organize your code. Previously known as internal modules, namespaces in TypeScript are based on an early draft of the ECMAScript modules.
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:
So:
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With