create a singleton in typescript

To create a singleton in TypeScript, you can use the object-oriented programming pattern known as the Singleton pattern. This pattern is a creational pattern that ensures that a class has only one instance, and provides a global point of access to that instance.

Here's an example implementation in TypeScript:

index.ts
class Singleton {
  private static instance: Singleton;

  private constructor() {
    // Private constructor to prevent instantiation outside of the class
  }

  public static getInstance(): Singleton {
    if (!Singleton.instance) {
      Singleton.instance = new Singleton();
    }

    return Singleton.instance;
  }
}
323 chars
16 lines

In this implementation, the Singleton class has a private static property instance that holds the single instance of the class. The constructor is made private to prevent direct instantiation of the class.

The static method getInstance() provides global access to the single instance of the class. This method first checks if the instance exists, and if not, creates one.

You can then use the getInstance() method to access the single instance of the Singleton class throughout your application:

index.ts
const singleInstance = Singleton.getInstance();
48 chars
2 lines

Note that this implementation is not thread-safe, which may lead to issues in multi-threaded environments. If you need a thread-safe implementation, you can add a mutex or lock to the getInstance() method.

gistlibby LogSnag