How to define Singleton in TypeScript

前端 未结 20 666

What is the best and most convenient way to implement a Singleton pattern for a class in TypeScript? (Both with and without lazy initialisation).

相关标签:
20条回答
  • 2020-11-28 20:55
    namespace MySingleton {
      interface IMySingleton {
          doSomething(): void;
      }
      class MySingleton implements IMySingleton {
          private usePrivate() { }
          doSomething() {
              this.usePrivate();
          }
      }
      export var Instance: IMySingleton = new MySingleton();
    }
    

    This way we can apply an interface, unlike in Ryan Cavanaugh's accepted answer.

    0 讨论(0)
  • 2020-11-28 20:55

    This is a typescript decorator checking if multiple instances were accidentaly created against a service class that is designed to be singleton:

    https://www.npmjs.com/package/singleton-checker

    0 讨论(0)
提交回复
热议问题