Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 8507

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T01:47:08+00:00 2024-11-28T01:47:08+00:00

Organizing TypeScript code using namespaces

  • 60k

Written by Emmanuel John ✏️

Introduction

With the use of third-party libraries in enterprise software increasing, we often encounter the problem of polluted global namespaces, causing name collision between components in the global namespace. Therefore, we need to organize blocks of code using namespaces so that variables, objects, and classes are uniquely identified.

In this article, we will discuss namespaces, when you'll need them, and how to use them to enhance the organization of your TypeScript code.

Prerequisites

  • Knowledge of TypeScript
  • Familiarity with JavaScript

What are namespaces?

Namespaces are paradigm of organizing code so that variables, functions, interfaces, or classes are grouped together within a local scope in order to avoid naming conflicts between components in the global scope. This is one of the most common strategies to reduce global scope pollution.

While modules are also used for code organization, namespaces are easy to use for simple implementations. Modules offer some additional benefits like strong code isolation, strong support for bundling, re-exporting of components, and renaming of components that namespaces do not offer.

Why do we need namespaces?

Namespaces have these advantages:

  • Code reusability — The importance of namespaces for code reusability cannot be understated
  • Bloated global scope — Namespaces reduce the amount of code in the global scope, making it less bloated
  • Third-party libraries — With the increasing number of websites depending on third-party libraries, it's important to safeguard your code using namespaces to prevent same-name conflicts between your code and the third-party libraries
  • Distributed development — With distributed development becoming popular, pollution is almost unavoidable because it’s a lot easier for developers to use common variable or class names. This results in name collision and pollution of the global scope

Design considerations using namespaces

Implicit dependency order

Using namespaces while working with some external libraries will require an implicit implementation of dependency between your code and these libraries. This results in the stress of managing the dependencies yourself so that they are loaded correctly, because the dependencies can be error-prone.

If you find yourself in such a situation, using modules will save you the stress.

Node.js applications

For Node.js applications, modules are recommended over namespaces since modules are the de facto standard for encapsulation and code organization in Node.

Non-JavaScript content import

Modules are recommended over namespaces when dealing with non-JavaScript content since some module loaders such as SystemJS and AMD allow non-JavaScript content to be imported.

Legacy code

When working with a codebase that is no longer engineered but continually patched, using namespaces is recommended over modules.

Also, namespaces come in handy when porting old JavaScript code.

Exploring namespaces in TypeScript

Now that we have a shared understanding of what TypeScript namespaces are and why we need them, we can take a deeper dive into how to use them.

Given that TypeScript is a superset of JavaScript, it derives its namespace concept from JavaScript.

By default, JavaScript has no provision for namespacing because we have to implement namespaces using IIFE (Immediately Invoked Function Expression):

var Vehicle; (function (Vehicle) {     let name = "car"; })(Vehicle || (Vehicle = {})); 
Enter fullscreen mode Exit fullscreen mode

This is so much code for defining a namespace. Meanwhile, TypeScript does things differently.

Single-file namespacing

In TypeScript, namespaces are defined using the namespace keyword followed by a name of choice.

A single TypeScript file can have as many namespaces as needed:

namespace Vehicle {} namespace Animal {} 
Enter fullscreen mode Exit fullscreen mode

As we can see, TypeScript namespaces are a piece of syntactic cake compared to our JavaScript implementation of namespaces using the IIFE.

Functions, variables, and classes can be defined inside a namespace as follows:

namespace Vehicle {   const name = "Toyota"   function getName () {       return `${name}`   } } namespace Animal {   const name = "Panda"   function getName () {       return `${name}`   } } 
Enter fullscreen mode Exit fullscreen mode

The above code allows us to use the same variable and function name without collision.

Accessing functions, variables, objects, and classes outside a namespace

In order to access functions or classes outside their namespaces, the export keyword must be added before the function or class name as follows:

namespace Vehicle {   const name = "Toyota"   export function getName () {       return `${name}`   } } 
Enter fullscreen mode Exit fullscreen mode

Notice that we had to omit the export keyword with the variable because it should not be accessible outside the namespace.

Now, we can access the getName function as follows:

Vehicle.getName() //Toyota 
Enter fullscreen mode Exit fullscreen mode

Organizing code using nested namespaces

TypeScript allows us to organize our code using nested namespaces.

We can create nested namespaces as follows:

namespace TransportMeans {   export namespace Vehicle {     const name = "Toyota"     export function getName () {         return `${name}`     }   } } 
Enter fullscreen mode Exit fullscreen mode

Notice the export keyword before the Vehicle namespace. This allows the namespace to be accessible outside of the TransportMeans namespace.

We can also perform deep nesting of namespaces.

Our nested namespaces can be accessed as follows:

TransporMeans.Vehicle.getName() // Toyota 
Enter fullscreen mode Exit fullscreen mode

The namespace alias

For deeply nested namespaces, the namespace alias comes in handy to keep things clean.

Namespace aliases are defined using the import keyword as follows:

import carName= TransporMeans.Vehicle; carName.getName(); //Toyota 
Enter fullscreen mode Exit fullscreen mode

Multi-file namespacing

Namespaces can be shared across multiple TypeScript files. This is made possible by the reference tag.

Considering the following:

//constant.ts export const name = "Toyota"  //vehicle.ts <reference path = "constant.ts" /> export namespace Vehicle {   export function getName () {       return `${name}`   } } 
Enter fullscreen mode Exit fullscreen mode

Here, we had to reference the constant.ts file in order to access name:

//index.ts <reference path = "constant.ts" /> <reference path = "vehicle.ts" /> Vehicle.getName() // Toyota 
Enter fullscreen mode Exit fullscreen mode

Notice how we started our references with the highest-level namespace. This is how to handle references in multi-file interfaces. TypeScript will use this order when compiling the files.

We can instruct the compiler to compile our multi-file TypeScript code into a single JavaScript file with the following command:

 tsc --outFile index.js index.ts 
Enter fullscreen mode Exit fullscreen mode

With this command, the TypeScript compiler will produce a single JavaScript file called index.js.

Conclusion

In order to build scalable and reusable TypeScript applications, TypeScript namespaces are handy because they improve the organization and structure of our application.

In this article, we’ve been able to explore namespaces, when you need them, and how to implement them. Check out TypeScript Handbook: Namespaces for more information about namespaces.


LogRocket: Full visibility into your web apps

LogRocket Dashboard Free Trial Banner

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.

Try it for free.

typescriptwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.