How to define Singleton in TypeScript

前端 未结 20 761

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

    My solution for it:

    export default class Modal {
        private static _instance : Modal = new Modal();
    
        constructor () {
            if (Modal._instance) 
                throw new Error("Use Modal.instance");
            Modal._instance = this;
        }
    
        static get instance () {
            return Modal._instance;
        }
    }
    

提交回复
热议问题