How to define Singleton in TypeScript

前端 未结 20 762

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.

提交回复
热议问题