1

I have read (again) the docs of Typescript to clear things out about modules and namespaces but I still have some dark points.

  1. declare namespace Foo{}
  2. namespace Foo{}
  3. export namespace Foo{}

Among those 3 ways to create a namespace, what is the intended use of each one?

Let's say I want to create a Validation namespace and I have 3 files that contribute to that namespace. What is the correct way of doing this and how I am going to import(use) the code in Validation namespace from another file/module?

koninos
  • 4,969
  • 5
  • 28
  • 47

1 Answers1

2

What is the correct way of doing this and how I am going to import(use) the code in Validation namespace from another file/module?

When you are saying "import(use)" and "file/module" in a single question, you are asking about two very different situations, and the answer is different for each one.

There is no way to do that with import and modules. Each module is a distinct, separate scope, and if you define namespace Validation in each module you will create 3 different namespaces because declarations from different scopes are not merged. Well, you can break out of module scope by using declare global, but it defeats the stated purpose of modules - elimination of globals.

You can do that with files which are not modules - that is, files that don't have any toplevel import or export. But then, you are restricted to non-modular javascript (or typescript). Your namespace Validation will be in the global scope, you can't use import and modules, and you have to compile and concatenate all files together, producing single script suitable for loading with a <script> tag.

See also How do I use namespaces with TypeScript external modules?

As for specific syntax variants

declare namespace Foo {}

This declares that there exists namespace Foo, defined in some external file (not included in the current compilation), allowing to use Foo which is assumed to contain things declared within {} (and {} may contain only declarations, not definitions here)

namespace Foo {}

This creates namespace Foo

export namespace Foo {}

This also creates namespace Foo, but export can have different meaning, depending on where it appears in the source file (it also depends on whether the file is a module or not, but I don't want to go into details of how export is useful without modules).

If export is at the top level, it turns the file into a module, and makes Foo available for importing and using (but not extending) in other modules. If export is not at the top level, then again it depends: if it's in some exported namespace, it defines nested namespace, accessible by modules which imported that outer namespace. If it is in non-exported namespace, export has no effect I believe.

Community
  • 1
  • 1
artem
  • 46,476
  • 8
  • 74
  • 78