maja maja - 1 year ago 316
TypeScript Question

How to define Singleton in TypeScript

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

Answer Source

Singleton classes in TypeScript are generally an anti-pattern. You can simply use namespaces instead.

Useless singleton pattern

class Singleton {
    /* ... lots of singleton logic ... */
    public someMethod() { ... }

// Using
var x = Singleton.getInstance();

Namespace equivalent

namespace Singleton {
    export function someMethod() { ... }
// Usage
var x = Singleton; // If you need to alias it for some reason
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download