Using namespace spread over multiple module files in TypeScript

aaron-bond picture aaron-bond · Aug 13, 2015 · Viewed 24.6k times · Source

I've started work on a large-scale typescript project.

Right from the outset, I want to keep my files organized (this project will be split between lots of developers so order is very necessary).

I have been attempting to use modules / namespaces and splitting classes out into separate files for each one, with a folder holding the namespace.

The file structure is:

app.ts
\Classes
---- \Animals
---- ---- Mammals.ts
---- ---- Reptiles.ts

I then attempt to import all files in that namespace in app.ts using something like: import * as Animals from "./Classes/Animals"

As for the namespace files themselves, I have tried the following, with no success:

namespace Animals {
    export class Mammals {
        constructor() {
        }
    }
}

and also:

module Animals {
    export class Reptiles {
        constructor() {
        }
    }
}

Unfortunately, the path is never recognized (as it points to a folder and not a single file). Is this even possible? Having all my classes from a single namespace in one file will result in files which are thousands of lines long and for this project that is not maintainable.

I have also noticed that TypeScript 1.5 has support for tsconfig.json - however, having to add each file manually to the map is a sure-fire way of introducing issues when developers start adding classes.

NOTE: I'm using Visual Studio 2015, TypeScript 1.5 (I believe, not sure how to verify). I also have ES6 support turned on.

Answer

Vadim Macagon picture Vadim Macagon · Aug 15, 2015

Use re-exporting to create an external module that groups and exposes types from other modules:

// Classes/Animals.ts
export * from '.\Animals\Mammals';
export * from '.\Animals\Reptiles';

Then import the types from the new module as usual:

// app.ts
import * as Animals from '.\Classes\Animals'

let dog: Animals.Dog;
let snake: Animals.Snake;

Or

// app.ts
import { Dog, Snake } from '.\Classes\Animals'

let dog: Dog;
let snake: Snake;