How to define Singleton in TypeScript

前端 未结 20 760

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:44

    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();
    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 reason
    

提交回复
热议问题