What is the best and most convenient way to implement a Singleton pattern for a class in TypeScript? (Both with and without lazy initialisation).
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.
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