What is the best and most convenient way to implement a Singleton pattern for a class in TypeScript? (Both with and without lazy initialisation).
After scouring this thread and playing around with all the options above - I settled with a Singleton that can be created with proper constructors:
export default class Singleton {
private static _instance: Singleton
public static get instance(): Singleton {
return Singleton._instance
}
constructor(...args: string[]) {
// Initial setup
Singleton._instance = this
}
work() { /* example */ }
}
It would require an initial setup (in main.ts, or index.ts), which can easily be implemented by
new Singleton(/* PARAMS */)
Then, anywhere in your code, just call Singleton.instnace; in this case, to get work done, I would call Singleton.instance.work()