How to define Singleton in TypeScript

前端 未结 20 718

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

    Not a pure singleton (initialization may be not lazy), but similar pattern with help of namespaces.

    namespace MyClass
    {
        class _MyClass
        {
        ...
        }
        export const instance: _MyClass = new _MyClass();
    }
    

    Access to object of Singleton:

    MyClass.instance
    

提交回复
热议问题