I have a class that employs lazy initialisation.
class LazyWorker {
private state: string | undefined;
lazyInit() {
if (this.state === undefined) {
//A lot of statements here
//That are guaranteed to initialise the this.state property
this.state = 'aaa'
//I don't want to repeat those statements...
//DRY principle, right?
}
}
doSomething() {
this.lazyInit();
this.state.startsWith('doSomething');
}
doSomethingElse() {
this.lazyInit();
this.state.endsWith('doSomethingElse');
}
}
Unfortunately, in the doSomething
methods, the compiler complains that this.state
might be undefined
.
I can hack around compiler complaining by defining the property the following way, but it is inelegant and might give the false impression that the property is never undefined.
class LazyWorker {
private state: string = undefined as any as string;
Any elegant way around it?