The method you are trying to access in Typescript is not present on the specified class

Here is a code snippet that showcases the use of state handling in TypeScript:

type StateTypes = State1 | State2;
    
class State1 { 
    static handleA (): StateTypes { 
        // Do Something
        return State2; 
    }
    static handleB (): StateTypes {
        // Do Something
        return State1;
    }
}

class State2 { 
    static handleA (): StateTypes { 
        // Do Something
        return State1; 
    }
    static handleB (): StateTypes {
        // Do Something
        return State2;
    }
}


let currentState: StateTypes = State1;

for (/* some Condition*/){
    if(/* some Condition*/)
        currentState = currentState.handleA();
    else
        currentState = currentState.handleB();
}

The code executes without any errors but Typescript raises an issue stating that it cannot find the static method 'handlaA()' in class State1.

TS2339: Property 'handleA' does not exist on type 'StateTypes'.   Property 'handleA' does not exist on type 'State1'.

Answer №1

StateTypes = State1 | State2 indicates an instance of either State1 or State2. What you need is:

StateTypes = typeof State1 | typeof State2
. This references constructors rather than instances

Answer №2

It appears that the return State1 statement is not returning the expected result. To troubleshoot this issue, consider testing it in a simpler example:

class State2 { 
    static changeState (): State1 {
        return State1;
    }
}

class State1 { 
    static testMethod (): void {
        console.log("testing");
    }
}

In this scenario, we are aiming to obtain a reference to State1.

let currentState = State2.changeState();
currentState.testMethod();

However, the error message remains consistent:

Property 'test' does not exist on type 'State1'.

To address this issue, you could transform the state into an instance. By doing so, you can acquire a reference to a different state and replace it with an instance of the new state.

type currentState = State1 | State2;

class State2 { 
    getStateInstance(): State1 {
        return new State1();
    }
    displayMessage(): void {
        console.log("state two");
    }
}

class State1 { 
    getStateInstance(): State2 {
        return new State2();
    }
    displayMessage(): void {
        console.log("state one");
    }
}

let currentState = new State2();

// Request the new state
currentState = currentState.getStateInstance();
currentState.displayMessage();

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

Issue with alignment in the multiselect filter of a React data grid

In React Data Grid, there is a issue where selecting multiple filter options messes up the column headers. Is there a solution to display selected filter options above a line in a dropdown rather than adding them to the column header? The column header siz ...

Is there a way to achieve region collapsing and expanding using #region / #endregion in TypeScript within Visual Studio Community Edition 2019?

For a while now, we've been utilizing "region collapsing" in TypeScript as shown below: //#region GUI handlers ...code related to handling GUI events... //#endregion This method has functioned well in VS2015 CE and VS2017 CE, with a small "-" or "+" ...

What is the best way to incorporate multiple calculations in JavaScript?

As a newcomer to JavaScript, I am trying my hand at creating an online tax calculator for our website. While I can understand pre-written calculations, developing my own has proven to be challenging. The objective is simple: the user inputs their Gross Inc ...

The save changes feature is not effectively syncing with the database

So, I have a button that triggers a javascript function, which initiates an AJAX request to call an actionresult that is supposed to update my database. Javascript Function function changeDepartment() { // Initializing and assigning variables va ...

Encountering issues with running an AngularJS application (version 1.6) in Visual Studio following the activation of script

I am new to working on an angular 1.6 application and still learning the ropes. The project consists of an asp.net web api project that needs to be run before starting the angular project. Everything was running smoothly until I tried to debug a parameter ...

strictBindCallApply causing issues when working with generic parameters

Take a look at this slightly contrived code snippet: export function evaluate<T>(this: { value: T }) { return this.value; } class SomeClass { value: ''; constructor() { const result = evaluate.call(this); } } You might notice ...

Limiting the data types of array elements applies to variables, not to indexes

type Soccer = { ball: string } type Basketball = { jump: string } type Data = Soccer[] | Basketball[] if ('ball' in data[index]) { // type guard not effective here. <MyComponent something={data[index]} /> // data: Soccer[] | Basketball[] ...

Trouble with Add To Cart feature in React app due to issues with Context API

I have been following a tutorial located here. I followed the steps exactly and even checked the code on the related github repository, which matches. However, when I try to add a product to the cart by clicking the button, the state does not update. In Re ...

Tips for keeping MUI Autocomplete open even when the input field loses focus

I am currently working with a MUI autocomplete feature that includes a list of items and an edit icon next to each one. The edit icon allows the user to change the name of the option by rerendering it as a textfield. However, I have encountered an issue wh ...

Is it possible to increase Google+ shares without needing an API key for every single page?

Looking to retrieve the number of Google+ shares for each URL on a search results page using Ajax. Facebook and Twitter share counts have been successfully implemented: $.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + & ...

Sending asynchronous requests to handle data within various functions based on different links

I'm currently facing a major roadblock when it comes to resolving my issues with callbacks. I've gone through resources like How to return value from an asynchronous callback function? and How to return the response from an Ajax call?, among seve ...

Capture an image of a webpage and print it out

I am currently in the process of designing a web page and one of the key features I need is a button that allows users to print a selected area. After conducting several searches, I came across html2canvas as a potential solution. I proceeded to install it ...

I'm having some trouble with this search filter in Vue 2 - is it failing to display the items as expected

After struggling with this issue for over a week, I've hit a roadblock and need some assistance. I'm currently working on implementing a search filter in Vue 2 with Vuetify, but something isn't quite right. Here's a snippet of the sea ...

What is the best method to select a sibling element by its class name and then conceal it using solely Javascript?

Here is the HTML structure I am working with: <div id="xyz"> </div> <div class="content"> </div> I am looking to hide the element with a class named content based on the sibling element ID, which is xyz. In jQue ...

Add a third-party library file to Visual Studio

I'm currently working in Visual Studios and attempting to utilize the library provided at . However, I am encountering difficulties when trying to import the library. I have added the file to the project and attempted to use it within the Book.js (Vi ...

Why is Vue JS throwing an error stating "undefined is not an object"?

After creating a Vue app on a single page .html file served by django, which consists of multiple components, I decided to transition this project into a full-fledged Vue.js project using the Vue CLI. Initially, I thought it would be a simple task to trans ...

Error: Validation error encountered while validating recipe: _listId field is mandatory and must be provided

As a newcomer to node.js, I am attempting to create a cookbook restful API using nodejs. The goal is to have a list of recipes where each recipe is associated with a specific list selected by its id. However, I am encountering an issue while trying to retr ...

Unable to assign a boolean value to a data attribute using jQuery

I have a button on my page that has a special data attribute associated with it: <button id="manageEditContract" type="button" class="btn btn-default" data-is-allow-to-edit="@(Model.Contract.IsAllowToEdit)"> @(Model.Contract.IsAllowToEdit ? " ...

Optimizing express server dependencies for a smooth production environment

After developing an application with a React front end and a Node server on the backend, I found myself wondering how to ensure that all dependencies for the server are properly installed when deploying it on a container or a virtual machine. Running npm ...

What is the best way to change a javascript string into HTML so that it can be shown in a form?

I am struggling to find a solution to this issue. I am fairly new to jQuery and JavaScript, so please forgive me if my question seems basic. I am trying to call a cfc (ColdFusion) using jQuery and retrieve HTML data. However, when I receive the data, it ...