Utilize dynamic function assignment based on a condition, followed by utilization within a loop in TypeScript version 2.3.4

In order to optimize my loop, I have devised a strategy where a function is created to determine the correct treatment. This function then assigns the appropriate value to a variable that can be used within the loop.

The approach can be summarized as follows:


export class myClass{

ref;

Treatment1(){code}
Treatment2(){code}
Treatment3(){code}

selectTreatment(){
   if(condition1){
      ref = Treatment1()
   else if(condition2){
      ref = Treatment2()
   else (condition3){
      ref = Treatment3()
}

   executeTreatment(){
      setInterval(ref(),300)
   }


}

I suspect there may be an issue with the this keyword!


To address this concern, I came up with a revised solution:

export class myClass{

ref:any;

Treatment1(){code}
Treatment2(){code}
Treatment3(){code}

selectTreatment():Function{
   if(condition1){
      return ()=>{Treatment1()};
   else if(condition2){
      return ()=>{Treatment1()};
   else (condition3){
      return ()=>{Treatment1()};
}

   executeTreatment(){
      this.ref=this.selectTreatement();
      setInterval(ref(),300);
   }
}

Answer №1

The issue at hand is rather complex as there seems to be a lack of information regarding how the class in question is being utilized, much like what Sampath mentioned earlier. Specifically, it would be beneficial to see how functions such as selectTreatement and executeTreatmeant are being invoked. However, based on the provided code snippet, there are certain adjustments that should be made.

  1. One important thing to note is the usage of the this keyword. It is essential that all instances of ref within both executeTreatment and selectTreatment are preceded by this.

  2. Additionally, assigning ref = Treatment1() results in setting it to the output of Treatment1 rather than establishing a reference to it. This causes issues when trying to call ref within

    executeTreatment</code, unless <code>TreatmentX
    actually returns a function. To address this, consider modifying your selectTreatment assignments to something akin to this.ref = this.Treatment1;

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

Error with Typescript types when using Styled Components

After successfully setting up styled-components in react-native, I encountered an issue while trying to use it in a simple example with react-native-web: import * as React from 'react'; import styled from 'styled-components'; export d ...

Creating a new object instance within its own constructor

While delving into the inner workings of the Prisma ORM source code, I stumbled upon this specific section that caught my attention: export class MigrateDev implements Command { public static new(): MigrateDev { return new MigrateDev() } ... ...

Executing the calling statement once all function statements have been completed

I am currently working on a lengthy function that involves retrieving data from multiple levels of a database. getResult() { this.appService .getCountries() .subscribe( (countries: Country[]) => { this.countries = co ...

What approach is recommended for integrating mapStateToProps with Typescript?

When you attempt to replace the code with: function mapStateToProps(appState: ApplicationState, ownProps: any): MyComponentState { ... return new MyComponentState(someObject, isNew); } You may encounter this error message: mapStateToProps() in ...

Generating TypeScript Type Definitions for dynamic usage

In my client server application, I use REST calls for communication. To avoid using the wrong types by mistake, I have defined all RestCalls in a common file (excerpt): type def<TConnection extends Connections> = // Authentication ...

Web application is not making API calls

Currently, I am experimenting with calling data from an API to create a simple weather application for practice purposes. I have been using the inspect element feature in my Chrome browser to check if the console will show the data log, but unfortunately, ...

Arranging Data in Arrays using Angular 4 GroupBy Feature

I'm working with an array structured like this: var data = [ { student: "sam", English: 80, Std: 8 }, { student: "sam", Maths: 80, Std: 8 }, { student: "john", English: 80, Std: 8 }, { student: "j ...

What makes it permissible to use `declare const foo = 3` in TypeScript?

As I was working on creating a TypeScript declaration file, I discovered that it is permissible to declare a constant and assign a value to it. declare const foo = 1; // This is considered valid declare const bar = 'b'; // This is al ...

Steps to access email template through an Excel web add-in

Currently, I am developing a new addin that aims to extract data from Excel and insert it into a word document. The final step would be attaching this document to an email in Outlook. While I have managed to achieve this using Power Automate, I prefer to ...

What could be causing the table to display empty when we are passing data to the usetable function?

Visit Codesandbox to view Table While the header appears correctly, I noticed something strange. When I console log the data props, it shows all the necessary data. However, when I try to console.log row, there doesn't seem to be any single object re ...

Tips for launching a new page with a button click in React.js without relying on Routers

I am completely new to React and trying to figure out how to dynamically load a new page component within the main page without changing the URL. Essentially, I want to open up a fresh page upon clicking a button on the main page, displaying only the conte ...

Customized Generic Types in TypeScript based on optional property conditions

In my React/Typescript app, I currently have the following code snippet - export type GetPricingParams = { search_id: number, promo_code?: string, }; export type GetPricingData = { amount: number, currency: string, search_id: number, ...

The functionalities of $scope and this in AngularJS

Currently, I am developing a small application using angularjs. In this project, I am trying to implement a feature that involves deleting a contact. The functionality itself works perfectly fine, however, I am encountering an issue where the 'this.op ...

How can I transfer the status code from my C# class to my TypeScript client application in ASP.NET Core?

One of my challenges involves working with the ProjectDecommissionRequestController controller and a TypeScript client app. The TypeScript client app is designed to print specific strings based on status codes, such as displaying a generic error message fo ...

In JavaScript, the function will return a different object if the string in an array matches the

My task involves working with a simple array of string ids and objects. Upon initial load, I am matching these Ids with the objects and setting the checked property to true. const Ids = ['743156', '743157'] [ { "id&quo ...

Validation for Zod does not appear to be activating when necessary input is missing

Can someone help me figure out why the validation in my Zod schema for a string input is not working as expected? Here's what I have: const nameSchema = z.string({ required_error: "Name is required", invalid_type_error: "Name ...

There was no corresponding state found in the storage for OidcClient.readSigninResponseState using oidc-client in conjunction with React and Typescript

While browsing through related threads on the topic, I found that many of them are inactive or lack a definitive solution. In my project, I am working on a client using react and typescript. I have integrated the oidc-client module to interact with an ext ...

Encountering an error with d3.line() in angular2 when combining d3v4 with Typescript. The x function is not working as expected

So here's my setup... import { D3Service, D3, Selection } from 'd3-ng2-service'; interface ChartData { q: number, p: number } export class GraphComponent implements OnInit{ private d3; private x1; private y; construc ...

The process of obtaining the generic return type of a method in a Typescript class that has been instantiated through a factory-like function

The following code example illustrates an issue where TypeScript is unable to infer the generic type U in the fooBar function, leading to the return type of fooRef.doIt() being unknown. What is the reason for this behavior and what modifications are requ ...

Choose between Typescript type a and Typescript type b

I am currently working with two interfaces: interface IComment extends IData { comment: string; } interface IHistory extends IData{ differences: any[]; timeStamp: number; } Both of these interfaces extend another interface: interface IData { use ...