Namespaces | Typescript
First steps#
Let's start with the program we'll be using as our example throughout this page.
Validators in a single file#
Namespacing#
As we add more validators, we're going to want to have some kind of organization scheme so that we can keep track of our types and not worry about name collisions with other objects. Instead of putting lots of different names into the global namespace, let's wrap up our objects into a namespace.
In this example, we'll move all validator-related entities into a namespace called Validation.
Because we want the interfaces and classes here to be visible outside the namespace, we preface them with export.
Conversely, the variables lettersRegexp and numberRegexp are implementation details, so they are left unexported and will not be visible to code outside the namespace.
Namespaced Validators#
Splitting Across Files#
Multi-file namespaces#
Validation.ts#
LettersOnlyValidator.ts#
ZipCodeValidator.ts#
Test.ts#
Once there are multiple files involved, we'll need to make sure all of the compiled code gets loaded. There are two ways of doing this.
First, we can use concatenated output using the --outFile flag to compile all of the input files into a single JavaScript output file:
The compiler will automatically order the output file based on the reference tags present in the files. You can also specify each file individually:
Alternatively, we can use per-file compilation (the default) to emit one JavaScript file for each input file.
If multiple JS files get produced, we'll need to use <script> tags on our webpage to load each emitted file in the appropriate order, for example:
MyTestPage.html (excerpt)#
Aliases#
Another way that you can simplify working with namespaces is to use import q = x.y.z to create shorter names for commonly-used objects.
Not to be confused with the import x = require("name") syntax used to load modules, this syntax simply creates an alias for the specified symbol.
Working with Other JavaScript Libraries#
To describe the shape of libraries not written in TypeScript, we need to declare the API that the library exposes. Because most JavaScript libraries expose only a few top-level objects, namespaces are a good way to represent them.