DEV Community

Cover image for TypeScript: namespace VS class
Pierre-Henry Soria ✨
Pierre-Henry Soria ✨

Posted on

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! 🤠

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 🤗