snippettypescriptCritical
How to define Singleton in TypeScript
Viewed 0 times
howtypescriptsingletondefine
Problem
What is the best and most convenient way to implement a Singleton pattern for a class in TypeScript? (Both with and without lazy initialisation).
Solution
Singleton classes in TypeScript are generally an anti-pattern. You can simply use namespaces instead.
Useless singleton pattern
Namespace equivalent
Useless singleton pattern
class Singleton {
/* ... lots of singleton logic ... */
public someMethod() { ... }
}
// Using
var x = Singleton.getInstance();
x.someMethod();Namespace equivalent
export namespace Singleton {
export function someMethod() { ... }
}
// Usage
import { SingletonInstance } from "path/to/Singleton";
SingletonInstance.someMethod();
var x = SingletonInstance; // If you need to alias it for some reasonCode Snippets
class Singleton {
/* ... lots of singleton logic ... */
public someMethod() { ... }
}
// Using
var x = Singleton.getInstance();
x.someMethod();export namespace Singleton {
export function someMethod() { ... }
}
// Usage
import { SingletonInstance } from "path/to/Singleton";
SingletonInstance.someMethod();
var x = SingletonInstance; // If you need to alias it for some reasonContext
Stack Overflow Q#30174078, score: 111
Revisions (0)
No revisions yet.