Search⌘ K
AI Features

Multiple Exports and Namespaces

Explore how to organize TypeScript code using multiple exports and namespaces within modules. Learn to import classes, functions, and interfaces either individually or via namespaces, and understand the use of default exports to manage module content. This lesson helps you grasp module structuring for cleaner and scalable TypeScript applications.

Multiple exports

When working with external libraries—that is, libraries that have been published for general consumption—it is common practice for a published library to export all classes, functions, and interfaces from a single module file.

This means that we do not need to know how this library is structured or how complex the class hierarchy is internally; we simply import the entire library from one file.

As an example of this technique, suppose we have a file named modules/MultipleExports.ts, as follows:

C++
// This is a TypeScript code that exports two classes, MultipleClass1
// and MultipleClass2, using the 'export' keyword.
export class MultipleClass1 {}
export class MultipleClass2 {}
// It's worth noting that these classes are empty, meaning they don't have any properties
// or methods defined within them.
  • We export two classes from this module file, which are named MultipleClass1 and MultipleClass2.

We can then import both of these classes in our modules_main.ts file as follows:

C++
// Importing MultipleClass1 and MultipleClass2 from the "MultipleExports" module using
// destructuring syntax
import { MultipleClass1, MultipleClass2 }
from "./modules/MultipleExports";
// Instantiating a new object of class MultipleClass1 and assigning it to the variable "mc1"
let mc1 = new MultipleClass1();
// Instantiating a new object of class MultipleClass2 and assigning it to the variable "mc2"
let mc2 = new MultipleClass2();
...