Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use namespaces with TypeScript external modules?

I have some code:

baseTypes.ts

export namespace Living.Things {   export class Animal {     move() { /* ... */ }   }   export class Plant {     photosynthesize() { /* ... */ }   } } 

dog.ts

import b = require('./baseTypes');  export namespace Living.Things {   // Error, can't find name 'Animal', ??   export class Dog extends Animal {     woof() { }   } } 

tree.ts

// Error, can't use the same name twice, ?? import b = require('./baseTypes'); import b = require('./dogs');  namespace Living.Things {   // Why do I have to write b.Living.Things.Plant instead of b.Plant??   class Tree extends b.Living.Things.Plant {    } } 

This is all very confusing. I want to have a bunch of external modules all contribute types to the same namespace, Living.Things. It seems that this doesn't work at all -- I can't see Animal in dogs.ts. I have to write the full namespace name b.Living.Things.Plant in tree.ts. It doesn't work to combine multiple objects in the same namespace across file. How do I do this?

like image 358
Ryan Cavanaugh Avatar asked May 20 '15 18:05

Ryan Cavanaugh


People also ask

How do namespaces work in TypeScript?

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.

Does TypeScript have namespaces?

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.

How can we access a class of module from outside in TypeScript?

So, all variables, classes, functions, etc. that are declared in a module are not accessible outside the module. A module can be created using the keyword export and a module can be used in another module using the keyword import . In TypeScript, files containing a top-level export or import are considered modules.

Is a namespace a module?

1. A module is a way which is used to organize the code in separate files and can execute in their local scope, not in the global scope. A namespace is a way which is used for logical grouping of functionalities with local scoping.


2 Answers

Candy Cup Analogy

Version 1: A cup for every candy

Let's say you wrote some code like this:

Mod1.ts

export namespace A {     export class Twix { ... } } 

Mod2.ts

export namespace A {     export class PeanutButterCup { ... } } 

Mod3.ts

export namespace A {      export class KitKat { ... } } 

You've created this setup: enter image description here

Each module (sheet of paper) gets its own cup named A. This is useless - you're not actually organizing your candy here, you're just adding an additional step (taking it out of the cup) between you and the treats.


Version 2: One cup in the global scope

If you weren't using modules, you might write code like this (note the lack of export declarations):

global1.ts

namespace A {     export class Twix { ... } } 

global2.ts

namespace A {     export class PeanutButterCup { ... } } 

global3.ts

namespace A {      export class KitKat { ... } } 

This code creates a merged namespace A in the global scope:

enter image description here

This setup is useful, but doesn't apply in the case of modules (because modules don't pollute the global scope).


Version 3: Going cupless

Going back to the original example, the cups A, A, and A aren't doing you any favors. Instead, you could write the code as:

Mod1.ts

export class Twix { ... } 

Mod2.ts

export class PeanutButterCup { ... } 

Mod3.ts

export class KitKat { ... } 

to create a picture that looks like this:

enter image description here

Much better!

Now, if you're still thinking about how much you really want to use namespace with your modules, read on...


These Aren't the Concepts You're Looking For

We need to go back to the origins of why namespaces exist in the first place and examine whether those reasons make sense for external modules.

Organization: Namespaces are handy for grouping together logically-related objects and types. For example, in C#, you're going to find all the collection types in System.Collections. By organizing our types into hierarchical namespaces, we provide a good "discovery" experience for users of those types.

Name Conflicts: Namespaces are important to avoid naming collisions. For example, you might have My.Application.Customer.AddForm and My.Application.Order.AddForm -- two types with the same name, but a different namespace. In a language where all identifiers exist in the same root scope and all assemblies load all types, it's critical to have everything be in a namespace.

Do those reasons make sense in external modules?

Organization: External modules are already present in a file system, necessarily. We have to resolve them by path and filename, so there's a logical organization scheme for us to use. We can have a /collections/generic/ folder with a list module in it.

Name Conflicts: This doesn't apply at all in external modules. Within a module, there's no plausible reason to have two objects with the same name. From the consumption side, the consumer of any given module gets to pick the name that they will use to refer to the module, so accidental naming conflicts are impossible.


Even if you don't believe that those reasons are adequately addressed by how modules work, the "solution" of trying to use namespaces in external modules doesn't even work.

Boxes in Boxes in Boxes

A story:

Your friend Bob calls you up. "I have a great new organization scheme in my house", he says, "come check it out!". Neat, let's go see what Bob has come up with.

You start in the kitchen and open up the pantry. There are 60 different boxes, each labelled "Pantry". You pick a box at random and open it. Inside is a single box labelled "Grains". You open up the "Grains" box and find a single box labelled "Pasta". You open the "Pasta" box and find a single box labelled "Penne". You open this box and find, as you expect, a bag of penne pasta.

Slightly confused, you pick up an adjacent box, also labelled "Pantry". Inside is a single box, again labelled "Grains". You open up the "Grains" box and, again, find a single box labelled "Pasta". You open the "Pasta" box and find a single box, this one is labelled "Rigatoni". You open this box and find... a bag of rigatoni pasta.

"It's great!" says Bob. "Everything is in a namespace!".

"But Bob..." you reply. "Your organization scheme is useless. You have to open up a bunch of boxes to get to anything, and it's not actually any more convenient to find anything than if you had just put everything in one box instead of three. In fact, since your pantry is already sorted shelf-by-shelf, you don't need the boxes at all. Why not just set the pasta on the shelf and pick it up when you need it?"

"You don't understand -- I need to make sure that no one else puts something that doesn't belong in the 'Pantry' namespace. And I've safely organized all my pasta into the Pantry.Grains.Pasta namespace so I can easily find it"

Bob is a very confused man.

Modules are Their Own Box

You've probably had something similar happen in real life: You order a few things on Amazon, and each item shows up in its own box, with a smaller box inside, with your item wrapped in its own packaging. Even if the interior boxes are similar, the shipments are not usefully "combined".

Going with the box analogy, the key observation is that external modules are their own box. It might be a very complex item with lots of functionality, but any given external module is its own box.


Guidance for External Modules

Now that we've figured out that we don't need to use 'namespaces', how should we organize our modules? Some guiding principles and examples follow.

Export as close to top-level as possible

  • If you're only exporting a single class or function, use export default:

MyClass.ts

export default class SomeType {   constructor() { ... } } 

MyFunc.ts

function getThing() { return 'thing'; } export default getThing; 

Consumption

import t from './MyClass'; import f from './MyFunc'; var x = new t(); console.log(f()); 

This is optimal for consumers. They can name your type whatever they want (t in this case) and don't have to do any extraneous dotting to find your objects.

  • If you're exporting multiple objects, put them all at top-level:

MyThings.ts

export class SomeType { ... } export function someFunc() { ... } 

Consumption

import * as m from './MyThings'; var x = new m.SomeType(); var y = m.someFunc(); 
  • If you're exporting a large number of things, only then should you use the module/namespace keyword:

MyLargeModule.ts

export namespace Animals {   export class Dog { ... }   export class Cat { ... } } export namespace Plants {   export class Tree { ... } } 

Consumption

import { Animals, Plants} from './MyLargeModule'; var x = new Animals.Dog(); 

Red Flags

All of the following are red flags for module structuring. Double-check that you're not trying to namespace your external modules if any of these apply to your files:

  • A file whose only top-level declaration is export module Foo { ... } (remove Foo and move everything 'up' a level)
  • A file that has a single export class or export function that isn't export default
  • Multiple files that have the same export module Foo { at top-level (don't think that these are going to combine into one Foo!)
like image 94
Ryan Cavanaugh Avatar answered Oct 31 '22 06:10

Ryan Cavanaugh


Nothing wrong with Ryan's answer, but for people who came here looking for how to maintain a one-class-per-file structure while still using ES6 namespaces correctly please refer to this helpful resource from Microsoft.

One thing that's unclear to me after reading the doc is: how to import the entire (merged) module with a single import.

Edit Circling back to update this answer. A few approaches to namespacing emerge in TS.

All module classes in one file.

export namespace Shapes {     export class Triangle {}     export class Square {}       } 

Import files into namespace, and reassign

import { Triangle as _Triangle } from './triangle'; import { Square as _Square } from './square';  export namespace Shapes {   export const Triangle = _Triangle;   export const Square = _Square; } 

Barrels

// ./shapes/index.ts export { Triangle } from './triangle'; export { Square } from './square';  // in importing file: import * as Shapes from './shapes/index.ts'; // by node module convention, you can ignore '/index.ts': import * as Shapes from './shapes'; let myTriangle = new Shapes.Triangle(); 

A final consideration. You could namespace each file

// triangle.ts export namespace Shapes {     export class Triangle {} }  // square.ts export namespace Shapes {     export class Square {} } 

But as one imports two classes from the same namespace, TS will complain there's a duplicate identifier. The only solution as this time is to then alias the namespace.

import { Shapes } from './square'; import { Shapes as _Shapes } from './triangle';  // ugh let myTriangle = new _Shapes.Shapes.Triangle(); 

This aliasing is absolutely abhorrent, so don't do it. You're better off with an approach above. Personally, I prefer the 'barrel'.

like image 36
Jefftopia Avatar answered Oct 31 '22 06:10

Jefftopia