Lazy

source

Lazily initialises a value. Useful for singleton patterns.

Usage:

const myValue = new Lazy(() => new ExpensiveThing());
// later...
const value = myValue.get();

A class can be made into a singleton by storing a private Lazy object and exposing it via a get() method. (For a true singleton, mark the constructor protected or private as well so that it cannot be instantiated from outside the class.)

class MySingleton {
  private static readonly lazy = new Lazy(() => new this());
  static get(): MySingleton {
    return this.lazy.get();
  }

  private constructor() {}

  // ...
}

Constructors

new Lazy<T>(initialise: Function): Lazysource

Constructs a new Lazy wrapper with an initialisation callback that constructs the actual value.

Properties

readonlyinitialise: Functionsource

value: Tsource

Methods

Instance methods

get(): Tsource

Returns the wrapped value, constructing it by invoking the initialisation callback on the first access.