DEV Community

Cover image for TypeScript: Namespace VS Class
Pierre-Henry Soria ✨
Pierre-Henry Soria ✨

Posted on • Edited on

4 1

TypeScript: Namespace VS Class

TypeScript: Would you better wrap functions in class or namespace?

In this article, we will see if it is more judicious to store functions in a namespace or a class, based on the size and complexity of the application.

// namespace
export namespace UserModel {
  type uuid = string;

  interface User {
    id: uuid;
    username: string;
    firstName: string;
    lastName: string;
    password: string;
    sex: string;
    age: number;
  }

  const users = new Map();

  export function createUser(user: User) {
    const userKey = getUserKey(user.id);
    users.set(userKey, user);
  }

  function getUserKey(id: uuid) {
    return `id${id}`;
  }
}

// usage
UserModel.createUser(user);
Enter fullscreen mode Exit fullscreen mode
// class
export class UserModel {
  // ...
  public createUser(user: User) {
    const userKey = this.getUserKey(user.id);
    users.set(userKey, user);
  }

  private getUserKey(id: uuid) {
    return `id${id}`;
  }
}

// usage
const userModel = new UserModel();
userModel. createUser(user);
Enter fullscreen mode Exit fullscreen mode

As you can see in the above code, there are two different ways to organize and encapsulate your code within a scope, namely, within a traditional class or a simple namespace.

Although adding your code to a namespace instead of a class will not bring any of the OOP features and advantages you could have with a class, it still allows for elegant and simple usage of your code while isolating it from your application's global scope.

Calling another function within the same namespace is exactly like calling any other function, whereas calling a function within a class requires using the this keyword, and each function declaration is specified by its access modifiers.

In term of readability and avoid conflicts with identical functions, declaring namespaces can be an excellent technique in small projects.


I can't wait to hear from your feedback / thoughts in comments! 🤠

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (1)

Collapse
 
pierre profile image
Pierre-Henry Soria ✨

Feel free to share your thoughts / feedback 🤩 Always happy to discuss if you would like to 🤗

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more