From typescript-eslint docs:
Custom TypeScript modules (
module foo {}
) and namespaces (namespace foo {}
) are considered outdated ways to organize TypeScript code. ES2015 module syntax is now preferred (import
/export
).
From Typescripts docs
Modules can contain both code and declarations.
Modules also have a dependency on a module loader (such as CommonJs/Require.js) or a runtime which supports ES Modules. Modules provide for better code reuse, stronger isolation and better tooling support for bundling.
It is also worth noting that, for Node.js applications, modules are the default and we recommended modules over namespaces in modern code.
My goal with this question is to find out why the module syntax is preferred over namespaces.
Here is what I've been doing so far:
PROJECT_TYPES.d.ts
I have multiple d.ts
files where I declare namespaces containing the types that I use across my project's source files.
declare namespace MY_NAMESPACE {
type FOO = "FOO"
}
Doing it like this, I can do the following inside any source file of my project:
someFile.ts
const foo: MY_NAMESPACE.FOO = "FOO";
And it works without the need of any import
/export
.
Notes:
- I'm using
d.ts
files because those files do not contain anyimport
/export
code. - I'm using
declare namespace
instead of justnamespace
because without thedeclare
keyword I get a@typescript-eslint/no-unused-vars
warning.
Considering that MY_NAMESPACE
is a unique name, should this be considered a bad practice? In this scenario, is there a reason I should use modules
over namespaces
? Should I not use d.ts
files?
I mean, the Typescript docs mentions that:
Modules provide for better code reuse, stronger isolation and better tooling support for bundling.
But I don't think I'm losing any of those benefits by following the pattern I described above, since all my "real" actual compiled result code are separated in modules. But why my types should be solely in modules?