I am getting the error:
TS2365: Operator '===' cannot be applied to types 'ExampleState.Unsaved' and 'ExampleState.Saving'.
When comparing an enum against a mutable member variable:
enum ExampleState {
Unset = -1,
Unsaved = 0,
Saving = 1,
Saved = 2
}
class Example {
private state : ExampleState = ExampleState.Unset;
public Save() {
if (this.state === ExampleState.Unsaved) {
this.BeginSaving();
while (this.state === ExampleState.Saving) { // !error!
this.CommitSave();
}
}
}
private BeginSaving() {
this.state = ExampleState.Saving;
}
private CommitSave() {
this.state = ExampleState.Saved;
}
}
The real example is an async method that performs multiple attempts at saving - this has been simplified to just illustrate the error.
Typescript doesn't seem to understand that this variable is mutable and overly aggressively assuming that it is not being changed. Why is this happening and what is the work-around?
while (this.state as any === ExampleState.Saving)as a workaround. But I suggest you to submit the case to the TypeScript team.while (this.state as ExampleState === ExampleState.Saving)