Needless Namespacing
If you’re converting a program from namespaces to modules, it can be easy to end up with a file that looks like this:
-
shapes.ts
export namespace Shapes { export class Triangle { /* ... */ } export class Square { /* ... */ } }
The top-level module here Shapes
wraps up Triangle
and Square
for no reason. This is confusing and annoying for consumers of your module:
-
shapeConsumer.ts
import * as shapes from "./shapes"; let t = new shapes.Shapes.Triangle(); // shapes.Shapes?
A key feature of modules in TypeScript is that two different modules will never contribute names to the same scope. Because the consumer of a module decides what name to assign it, there’s no need to proactively wrap up the exported symbols in a namespace.
To reiterate why you shouldn’t try to namespace your module contents, the general idea of namespacing is to provide logical grouping of constructs and to prevent name collisions. Because the module file itself is already a logical grouping, and its top-level name is defined by the code that imports it, it’s unnecessary to use an additional module layer for exported objects.
Here’s a revised example:
-
shapes.ts
export class Triangle { /* ... */ } export class Square { /* ... */ }
-
shapeConsumer.ts
import * as shapes from "./shapes"; let t = new shapes.Triangle();
Please login to continue.