4

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?

4
  • You could use while (this.state as any === ExampleState.Saving) as a workaround. But I suggest you to submit the case to the TypeScript team. Commented Oct 11, 2017 at 9:13
  • 1
    Same suggestion, although I'd rather do: while (this.state as ExampleState === ExampleState.Saving) Commented Oct 11, 2017 at 12:07
  • 2
    There is a open issues about that: github.com/Microsoft/TypeScript/issues/9998 Commented Oct 11, 2017 at 12:15
  • 1
    In the issue posted by @Magu, there is another workaround. I think it's the best solution. Commented Oct 11, 2017 at 13:36

1 Answer 1

2

This is an know issus from the Control flow analysis.

As another workaround you can create a wrapper method for the state property. (Thanks @Paleo)

Visit the Playground.

enum ExampleState {
    Unset = -1,
    Unsaved = 0,
    Saving = 1,
    Saved = 2
}

class Example {

    private state : ExampleState = ExampleState.Unset;

    private State() { 
        return this.state;
    }

    public Save() {
        if (this.State() === ExampleState.Unsaved) {
            this.BeginSaving();
            while (this.State() === ExampleState.Saving) { 
                this.CommitSave();
            }
        }
    }

    private BeginSaving() {
        this.state = ExampleState.Saving;
    }

    private CommitSave() {
        this.state = ExampleState.Saved;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.