Error in Typescript compiler occurs when comparing mutable enum member variables

Encountering the following error message:

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

While trying to compare an enum 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 scenario in question involves an asynchronous function that makes multiple save attempts - however, it has been simplified here for clarity.

It seems that Typescript is not recognizing that the variable can be changed and is making assumptions incorrectly. What could be causing this issue and how can it be resolved?

Answer №1

Here is an known issue related to Control flow analysis.

One workaround suggested is to create a wrapper method for the state property. (Credits to @Paleo)

Explore 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;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue with React Redux and Typescript involving the AnyAction error while working on implementing

While integrating redux-persist into my React project, I encountered an error. Previously, Redux was working smoothly, but upon the addition of redux-persist, I started receiving this error message: Types of property 'dispatch' are incompatib ...

Managing an exception for the second time

In my project, I recently extended the ExceptionHandler class in Angular: import {Injectable, ExceptionHandler} from '@angular/core'; export class FirstError extends Error { handle() { console.log("This is firstError handler"); ...

Edge is experiencing a slowdown when utilizing ng-bind-html

I've been using ng-bind-html to bind HTML content to a div element. However, when I attempt to bind larger amounts of HTML, it can take around 5-6 seconds for the content to load. Interestingly, this issue seems to only occur in Chrome browser. I have ...

Develop a TypeScript Module that consolidates all exports

My Goal with TypeScript Modules I aim to streamline my TypeScript project by creating a module that contains all the necessary class exports. Currently, I find myself using relative import statements in my classes, which can make maintenance challenging i ...

Does the state remain unchanged when assigning an Angular service?

I am trying to grasp the inner workings of Angular. I have a standalone component called TestComponent that receives TestService as an injection. This component invokes the method this.testService.assign(). Later, a Guard injects the TestService and calls ...

Tips for handling changing form information with useState?

I am faced with a dilemma - I have a dynamic form with potentially hundreds of input fields, making it impractical to create a state for each one individually. My plan is to use an object with the unique key of each form field, but I could use some guidanc ...

Encountering a runtime issue with socket.io when using typescript that has been bundled by

Recently, I attempted to implement web sockets using socket.io in a Node server written in TypeScript with ExpressJS and bundled with Webpack. The server code is structured as follows: import * as Express from "express"; import * as SocketIO from "socket ...

Issue with Angular2 discount calculation formula malfunctioning

I'm encountering a rather perplexing issue with Angular2/Typescript. My goal is to compute the final price based on a specified discount value. Here's the formula I am using: row.priceList = row.pricePurchase + (row.pricePurchase * row.markUp / ...

Tips on how to reach an Angular component within a third-party library

I'm currently working on a web application that incorporates the Deezer player through the official JS SDK. I've run into an issue where I am unable to access my Angular component from within the Deezer event subscription. The arrow function does ...

Guide to resolving a Promise that returns an array in TypeScript

My goal is to retrieve an array in the form of a promise. Initially, I unzipped a file and then parsed it using csv-parse. All the resulting objects are stored in an array which is later returned. Initially, when I tried returning without using a promise, ...

Encountered an error when creating my own AngularJS module: Unable to instantiate

Attempting to dive into TypeScript and AngularJS, I encountered a perplexing error after following a tutorial for just a few lines. It appears that there may be an issue with my mydModule? angular.js:68 Uncaught Error: [$injector:modulerr] Failed to inst ...

Troubleshooting: Difficulty assigning a value to a nested object in Angular

I'm a beginner in Angular and TypeScript so please forgive me if this question seems silly. I am attempting to store the value of a returned object into a nested property within an object with a type of any. Unfortunately, it is not allowing me to do ...

Struggling with Angular 5 Facebook authentication and attempting to successfully navigate to the main landing page

I have been working on integrating a register with Facebook feature into an Angular 5 application. Utilizing the Facebook SDK for JavaScript has presented a challenge due to the asynchronous nature of the authentication methods, making it difficult to redi ...

What is the most efficient way to update data multiple times by mapping over an array of keys in a react hook?

My question might not be articulated correctly. I'm facing an issue with dynamically translating my webpage using Microsoft's Cognitive Services Translator. I created a react hook for the translator, which works well when I need to translate a si ...

What is the best way to import files in nodejs for tsc build and ts-node-dev compatibility?

While working with ts-node-dev, I have noticed that imported files must be named as "./api" or "./api.ts" during development. However, once the project is built using tsc, the file name needs to be "./api.js" (which is the sta ...

Tips on implementing npm's node-uuid package with TypeScript

Whenever I attempt to utilize node-uuid in TypeScript, I encounter the following issue: Cannot find module uuid This error occurs when I try to import the uuid npm package. Is there a way to successfully import the npm uuid package without encountering ...

RxJS: Observable.never() acts like an eternal subscription

Currently, I am working with rxjs version 5.5.6. Below is a snippet of code that showcases a specific behavior: Observable.of(1, 2) .do(a => { console.log(a); let d:string = null; let r = d.length; // this line throws a nu ...

Iterating through the nested JSON causes an error when trying to set properties of undefined

My dataset is structured as a nested JSON, with the main object named bwaResult. Within this object, there are three primary groups: actBwa, fcBwa, and planBwa. Each of these groups contains yearly data and results that include years. I am trying to organi ...

Angular is not providing the anticipated outcome

I'm new to Angular (7) and I'm encountering an issue while trying to retrieve the status code from an HTTP request. Here's the code snippet used in a service : checkIfSymbolExists() { return this.http.get(this.url, { observe: 'res ...

The Material Autocomplete Input is still displaying [Object object] even after implementing the displayWith property

Currently, I am utilizing an input with mat-autocomplete to choose an option from a list of objects (each object contains ID, name, surname, etc.). My goal is to have the formControl's value represent the entire object rather than just the name. This ...