How to define Singleton in TypeScript

前端 未结 20 753

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

    Here is yet another way to do it with a more conventional javascript approach using an IFFE:

    module App.Counter {
        export var Instance = (() => {
            var i = 0;
            return {
                increment: (): void => {
                    i++;
                },
                getCount: (): number => {
                    return i;
                }
            }
        })();
    }
    
    module App {
        export function countStuff() {
            App.Counter.Instance.increment();
            App.Counter.Instance.increment();
            alert(App.Counter.Instance.getCount());
        }
    }
    
    App.countStuff();
    

    View a demo

提交回复
热议问题