TypeScript: Pattern: Lazy Singleton

September 17th, 2022

singleton.interface.ts

export default interface Singleton<T> {

getValue: () => T

}

foo.ts

class FooSingleton implements Singleton<Foo> [

private foo: Foo

 

getValue() {

if(!foo) this.foo = new Foo();

return this.foo;

}

}

 

const fooSingleton = new FooSingleton()

export default fooSingleton as Singleton<Foo>

 

Do keep in mind the disadvantages of the singleton pattern

 

(src: Design Patterns in TypeScript - Singleton | The Startup)