Declaring a field as lazy

KarolDepka picture KarolDepka · Mar 16, 2017 · Viewed 10.3k times · Source

In TypeScript, is there a syntax for declaring a field as lazily-initialized?

Like there is in Scala, for example:

lazy val f1 = new Family("Stevens")

Meaning that the field initializer would only run when the field is first accessed.

Answer

user663031 picture user663031 · Mar 17, 2017

I would use a getter:

class Lazy {
  private _f1;

  get f1() {
    return this._f1 || (this._f1 = expensiveInitializationForF1());
  }

}

Yes, you could address this with a decorator, but that might be overkill for simple cases.