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)
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:
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.
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.
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.
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.
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;
}
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.
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.
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.
interface Window {
customMethod: () => void;
}
window.customMethod = function () {
console.log("This is a custom method on the window object.");
};
// 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.
Comments
Recent Work
Basalt
basalt.softwareFree desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.
BidBear
bidbear.ioBidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.