TypeScript / TypeScript Modules and Namespaces

Organizing Code with Namespaces

In this tutorial, you will learn how to use namespaces in TypeScript to organize your code. Namespaces can help prevent naming collisions and improve code readability.

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Covers the module system in TypeScript, including imports, exports, and namespaces.

Introduction

In this tutorial, we will dive into the concept of Namespaces in TypeScript. We will discover how to use namespaces to organize our code, prevent naming collisions, and enhance our code readability.

You will learn:
- What namespaces are and their importance
- How to declare and use namespaces
- Best practices when working with namespaces

Prerequisites:
- Basic knowledge of TypeScript
- A development environment set up with TypeScript installed

Step-by-Step Guide

Understanding Namespaces

Namespaces are a TypeScript-specific way to organize your code. They are essentially a way to group related code under a common name, to avoid naming collisions and make code more readable.

Declaring a Namespace

In TypeScript, a namespace is defined using the namespace keyword, followed by the name of the namespace and a set of curly braces {}. The code that belongs to the namespace goes inside these braces.

namespace MyNamespace {
  // code goes here
}

Using a Namespace

To use a function or variable from a namespace, you prefix it with the namespace name followed by a dot ..

namespace MyNamespace {
  export function displayMessage() {
    console.log("Hello from MyNamespace!");
  }
}

MyNamespace.displayMessage(); // Outputs: "Hello from MyNamespace!"

Best Practices and Tips

  • Keep namespaces small and focused on a single concept.
  • Avoid global namespaces, strive to make them module-specific.
  • Always export the functions, classes, or variables you want to use outside the namespace.

Code Examples

Let's look at a more practical example:

namespace StringUtilities {
  export function toUpperCase(str: string): string {
    return str.toUpperCase();
  }

  export function toLowerCase(str: string): string {
    return str.toLowerCase();
  }
}

console.log(StringUtilities.toUpperCase("hello")); // Outputs: "HELLO"
console.log(StringUtilities.toLowerCase("WORLD")); // Outputs: "world"

In this example, we have a namespace StringUtilities that contains two functions: toUpperCase and toLowerCase. The export keyword is used to make these functions available outside the namespace.

Summary

In this tutorial, we learned about namespaces in TypeScript. We learned how to declare, use, and organize code using namespaces. We also covered some best practices when working with namespaces.

For further learning, explore how namespaces can be split across many files and how to use /// <reference> directive for this purpose.

Practice Exercises

  1. Create a namespace named MathUtilities with functions to add, subtract, multiply, and divide two numbers.

  2. Create a namespace named ArrayUtilities that includes functions to find the minimum and maximum number in an array.

Solutions
1. MathUtilities

namespace MathUtilities {
  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 {
    return a / b;
  }
}
  1. ArrayUtilities
namespace ArrayUtilities {
  export function findMin(arr: number[]): number {
    return Math.min(...arr);
  }

  export function findMax(arr: number[]): number {
    return Math.max(...arr);
  }
}

Try to use these namespaces and functions in your code.

Remember, the more you practice, the more comfortable you will become with namespaces in TypeScript. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

Favicon Generator

Create favicons from images.

Use tool

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help