Typescript compiler error comparing enum variable variables

I get an error message:

TS2365: Operator '===' cannot be applied to types 'ExampleState.Unsaved' and 'ExampleState.Saving'.

When comparing an enumeration with 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 asynchronous method that makes several save attempts - it's simplified to just illustrate the error.

Typescript does not seem to understand that this variable is volatile and overly aggressive suggests that it does not change. Why is this happening and what is happening around?

+4
source share
2 answers

This is a know issus from control flow analysis .

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

.

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;
    }
}
+2

, ExampleState.Unsaved - , (let x: ExampleState.Unsaved ). Typescript ,

if (this.state === ExampleState.Unsaved)

- - Typescript this.state ExampleState.Unsaved.

, , ( ):

type ExampleState = -1 | 0 | 1 | 2;
class Example {

    private state : ExampleState = -1;

    public Save() {
        if (this.state === 0) {
            this.BeginSaving();
            while (this.state === 1) {  // !error!
                this.CommitSave();
            }
        }
    }

    private BeginSaving() {
        this.state = 1;
    }

    private CommitSave() {
        this.state = 2;
    }
}

, @Paleo, , Typescript ( ​​- ). casting while. , while, JavaScript, .

while (this.state as ExampleState === ExampleState.Saving) {  // no error
    this.CommitSave();
}
0

Source: https://habr.com/ru/post/1687292/


All Articles