Skip to main content

TypeScript: Modules and NameSpaces

Intro

In TypeScript, modules are used to organize and reuse code. Just like they are in JavaScript. Anything involving import or export is dealing with modules.

There are two types of modules in TypeScript:

  • Internal Modules (Namespaces)
  • External Modules (Modules)
warning

In TypeScript 1.5+ the nomenclature has changed. "Internal modules" are now "namespaces" and "external modules" are now "modules".

This change was made to align with the ECMAScript 6 module syntax.

We will stick to using the new terminology in this article.

Namespaces

typescriptlang.org > namespaces

In TypeScript, namespaces are used to organize and share code across multiple files. Namespaces allow you to group related functionality into a single unit and prevent naming conflicts.

Here’s an example of how you can use namespaces in TypeScript:

myNamespace.ts
namespace MyNamespace {
export function doSomething() {
console.log("Doing something...");
}
}

// main.ts
/// <reference path="myNamespace.ts" />
MyNamespace.doSomething(); // Output: "Doing something..."

Namespaces are useful for organizing code into logical groups.

Namespace Augmentation

Namespace augmentation is a way to extend or modify existing namespaces. This is useful when you want to add new functionality to existing namespaces or to fix missing or incorrect declarations in third-party libraries.

Suppose you have a module that exports a namespace Library, and you want to add a new function to this namespace.

Step 1: Define the Original Namespace

First, define the original namespace in a module.

library.ts
export namespace Library {
export function greet(name: string): string {
return `Hello, ${name}!`;
}
}

Step 2: Augment the Namespace

Next, augment the Library namespace in another module.

augmentation.ts
import { Library } from "./library";

declare module "./library" {
namespace Library {
function farewell(name: string): string;
}
}

// Implement the augmented method
Library.farewell = function (name: string): string {
return `Goodbye, ${name}!`;
};

Step 3: Use the Augmented Namespace

Finally, use the augmented namespace in your application.

app.ts
import { Library } from "./library";
import "./augmentation";

console.log(Library.greet("Alice")); // Output: Hello, Alice!
console.log(Library.farewell("Alice")); // Output: Goodbye, Alice!

Modules

Formerly known as external modules, these are the standard modules that JavaScript veterans will be used to.

Modules are used to organize code across multiple files. They are defined using the “export” keyword in one file and the “import” keyword in another file. External modules in TypeScript follow the CommonJS or ES modules standards.

For example you will create a utility file with some functions and then import them into your main file.

mathUtils.ts
export function add(a: number, b: number): number {
return a + b;
}

export function subtract(a: number, b: number): number {
return a - b;
}

export function multiply(a: number, b: number): number {
return a * b;
}

export function divide(a: number, b: number): number {
if (b === 0) {
throw new Error("Division by zero is not allowed.");
}
return a / b;
}
app.ts
import { add, subtract, multiply, divide } from "./mathUtils";

const a = 10;
const b = 5;

console.log(`Addition of ${a} and ${b} is ${add(a, b)}`);
console.log(`Subtraction of ${a} and ${b} is ${subtract(a, b)}`);
console.log(`Multiplication of ${a} and ${b} is ${multiply(a, b)}`);
console.log(`Division of ${a} and ${b} is ${divide(a, b)}`);

Ambient Modules

Ambient modules in TypeScript are used to declare external modules or third-party libraries in a TypeScript program. Ambient modules provide type information for modules that have no TypeScript declarations, but are available in the global scope.

Example

Step 1: Create an Ambient Module Declaration

Suppose you are using a JavaScript library called awesome-library that does not have TypeScript type definitions. You can create a type declaration file for it.

awesome-library.d.ts
declare module "awesome-library" {
export function awesomeFunction(param: string): string;
export const awesomeVariable: number;
}

Step 2: Use the Ambient Module in Your TypeScript Code

Now, you can use the awesome-library module in your TypeScript code with type safety.

app.ts
import { awesomeFunction, awesomeVariable } from "awesome-library";

const result = awesomeFunction("Hello, world!");
console.log(result); // Assume it logs some awesome message

console.log(`Awesome Variable: ${awesomeVariable}`);

Global Augmentation

Global augmentation allows you to add or modify global variables and types. This is useful when you need to extend existing global objects, such as Window, Document, or Node, with additional properties or methods.

Example: Extending the Window Object

Suppose you want to add a custom method to the global Window object.

global.d.ts
interface Window {
customMethod: () => void;
}

window.customMethod = function () {
console.log("This is a custom method on the window object.");
};
app.ts
// Use the custom method on the window object
window.customMethod(); // Output: This is a custom method on the window object.

.d.ts files

The .d.ts in file names stands for "declaration file" in TypeScript. Declaration files are used to describe the shape of JavaScript code to the TypeScript compiler. They provide type information about an API that's written in plain JavaScript, allowing TypeScript to understand how to type-check code that uses that API.

Key Points about .d.ts Files

  • Type Information: .d.ts files provide type annotations for JavaScript code. They don't contain any implementation code; instead, they describe the types of variables, functions, classes, and modules.

  • Ambient Declarations: They often contain ambient declarations, which describe types for modules or global variables that exist at runtime.

  • Third-Party Libraries: When using third-party JavaScript libraries without TypeScript type definitions, you can use or create .d.ts files to provide those type definitions. Many popular libraries have type definitions available via DefinitelyTyped, a repository of high-quality TypeScript type definitions.

  • Automatic Inclusion: If you place .d.ts files in your project, TypeScript will automatically include them when type-checking your code.

Automated Amazon Reports

Automatically download Amazon Seller and Advertising reports to a private database. View beautiful, on demand, exportable performance reports.

bidbear.io