One of the challenges I am facing is dealing with lazy initialization in a particular class.
class LazyWorker {
private state: string | undefined;
lazyInit() {
if (this.state === undefined) {
//Numerous statements go here
//That will ultimately initialize the this.state property
this.state = 'aaa'
//I want to avoid repeating those statements...
//Following the DRY principle, correct?
}
}
doSomething() {
this.lazyInit();
this.state.startsWith('doSomething');
}
doSomethingElse() {
this.lazyInit();
this.state.endsWith('doSomethingElse');
}
}
However, the issue arises when using the doSomething
methods as the compiler warns that this.state
could be undefined
.
I found a workaround by defining the property like this, but it feels clumsy and can give the wrong impression that the property is never undefined.
class LazyWorker {
private state: string = undefined as any as string;
Is there a more elegant solution to overcome this issue?