While working in .NET, I came across the Lazy<T>
type which proved to be very helpful for tasks like lazy loading and caching. However, when it comes to TypeScript, I couldn't find an equivalent solution so I decided to create my own.
export interface Factory<TResult> { () : TResult; }
export class Lazy<T> {
factoryOutput : T;
isValueSet : boolean;
constructor(private factory : Factory<T>) { }
get value() {
if (!this.isValueSet) {
this.factoryOutput = this.factory();
this.isValueSet = true;
}
return this.factoryOutput;
}
}
Having to develop my own solution has raised some questions:
- Is there an existing alternative that I may have overlooked in TypeScript?
- Could there be any flaws in my approach to wanting a .NET-style
Lazy<T>
in TypeScript?