How to define Singleton in TypeScript

前端 未结 20 756

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

    I am surprised not to see the following pattern here, which actually looks very simple.

    // shout.ts
    class ShoutSingleton {
      helloWorld() { return 'hi'; }
    }
    
    export let Shout = new ShoutSingleton();
    

    Usage

    import { Shout } from './shout';
    Shout.helloWorld();
    

提交回复
热议问题