Are If-instanceof-statements considered harmful in Typescript?

   selectAction: (actionEvent) => {
        if (actionEvent instanceof Action1) { 
            // action1 body implementation
        } else if (actionEvent instanceof Action2) {
            // action2 body implementation
        } 
    }

This code snippet is designed to handle different types of actions with unique functionalities. However, relying on if-else conditions for each type of action may not be the most scalable solution. As new actions are added in the future, the code will become increasingly complex and require frequent updates.

Are there any alternative approaches to handling this scenario more efficiently?

Answer №1

Implement the concept of duck typing to eliminate the need for conditional statements. Source

Create a method named selection() within each type instance like Action1 and Action2, and so on, to define the desired functionality you wish to implement. Then simply invoke the selection() method without using any conditions. This way, depending on the type of instance, the corresponding selection() method will be executed.

Answer №2

There is no inherent issue with utilizing if/else in TypeScript.

Nevertheless, if you find yourself using instanceof, there is likely a more suitable alternative at your disposal. In such situations, it is highly recommended that the actions themselves should take responsibility for their execution:

selectAction: (actionEvent) => {
    actionEvent.execute();
}

...or

selectAction: (actionEvent) => {
    const action = /*...determine action from actionEvent...*/;
    action.execute();
}

...or a comparable approach (alternatively, you may directly use actionEvent.execute() instead of selectAction).

This concept revolves around polymorphism, wherein distinct objects adhere to the same interface and perform varying operations upon being invoked.

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

What steps should I take to resolve the error message "Error: srcmain.ts is not found in the TypeScript compilation?"

I've exhausted all possible solutions on StackOverflow and have even gone as far as uninstalling both Node and Angular three times in the span of three days. I'm completely stumped as to why this issue keeps occurring specifically when using "ng ...

Is there a way to individually apply loading to only the button that has been clicked in vuejs?

One problem I am facing is that when I click a specific button in a table, all buttons end up in loading mode. The table loops and displays data from an API, with a button embedded in each row. Upon clicking the button, it should send the ID of the clicked ...

Generating Components Dynamically in Angular 4 Based on User-Defined Input

I am interested in developing an innovative App using Angular 4 that enables the creation of components from various storage sources such as database, URLs, and server-stored files. The main objective is to allow users to design their own components for pe ...

Obtaining the value of an ion-toggle in Ionic2 using the ionChange

Below is the toggle I am referring to: <ion-toggle (ionChange)="notify(value)"></ion-toggle> I am looking for a way to retrieve the value of the toggle when it is clicked in order to pass it as a parameter to the notify method. Any suggestion ...

Modifying one instance of an object will automatically alter the other instance as well

Currently, I am working on developing a simple table in Angular where specific functions are applied to modify the table based on different conditions. These include sorting the data upon pressing the sort button and adding salutations based on the gender. ...

Divide the chosen option using the underscore symbol

I have implemented Material CSS in my web page design which includes a single select country list dropdown with specific values. <select id="select_id" name="select_id" required> <option value="8">select1_1</o ...

What changes can be made to this function in order for the arches to be positioned directly in front of the camera?

I devised a method that arranges arches in front of a camera, side by side: <!-- HTML --> <a-curvedimage v-for="(value, index) in model" :theta-length="42" :rotation="setThumbsRotation(value, index)"> </a-curvedimage> <a-camera ...

Choosing specific rows based on multiple conditions using if and if-else statements in R

In attempting to solve this particular issue, I utilized if and else if statements: If "TRUE1" is present in the column "check," then select rows with "TRUE1" If "TRUE1" is not present in the column "check," then choose rows with "TRUE2"; otherwise, selec ...

Guide to clearing cache for a specific route using the 'apicache' module

I've incorporated the NPM apicache library into my MERN application for API caching. My goal is to cache one of my requests and then refresh the cache when a request is made to another route (fetching new data). While I've successfully cached one ...

Tips for preventing visual glitches caused by inaccurate world coordinates in WebGL

Issue: Encountering rendering glitches while using world coordinates in the fragment shader to display a grid. The grid does not move uniformly when the plane it is rendered on is moved, resulting in one "half" moving while the other remains idle. Refer ...

Looping through a sequence of asynchronous tasks, utilizing the async/await syntax, writing data to

I'm currently working on a script to download pdf files from a specified URL and save them to my local disk. However, I have encountered an issue where I need each file to be downloaded one at a time with a one-second delay in between (to ensure that ...

What is the best way to send parameters to a callback function in a jQuery $.getJSON method?

Currently, I am attempting to utilize jQuery to access a custom API using Ajax/$.getJSON. In my code, I am trying to send a specific value to the Ajax callback method, but I am encountering an issue where this value is not being properly passed and instea ...

The functionality of jQuery date picker and time picker is compromised when the fields are generated dynamically

I am currently utilizing the jQuery code below to dynamically create multiple input fields, which include time pickers and date pickers. However, I am encountering an issue where they are not functioning as expected. $('#add_another_event').clic ...

showing a pop-up message when a specific javascript function is triggered

Here is a unique code snippet showcasing a customized dialog box created with HTML, CSS, and JavaScript. The dialog box is displayed when a button is clicked. <!DOCTYPE html> <html> <head> <style> /* Custom Modal Styles */ .modal { ...

Following the upgrade to version 6.3.3, an error appeared in the pipe() function stating TS2557: Expected 0 or more arguments, but received 1 or more

I need some assistance with rxjs 6.3.3 as I am encountering TS2557: Expected at least 0 arguments, but got 1 or more. let currentPath; const pipeArgs = path .map((subPath: string, index: number) => [ flatMap((href: string) => { con ...

Show the information obtained from the dropdown menu selection

Upon selecting a different item from the drop-down list, I want the specific data related to that field from the MySQL database to be displayed. Currently, I am able to retrieve the value of the selected item in the dropdown menu but encountering difficul ...

Show some text when the ReactJS icon is hovered over

As a beginner with React, I am trying to show text when the user hovers over an icon. Currently, I am using material-ui along with the latest version of Reactjs. Below is the code snippet that I last tried: return ( <List className={classes.list ...

Difficulty with Angular's Interpolation and incorporating elements

I've encountered an issue with String Interpolation while following an Angular course. In my server.component.ts file, I've implemented the same code as shown by the teacher in the course: import { Component } from "@angular/core"; @Component ( ...

Trouble arises when displaying data using AngularJS in an HTML environment

I'm currently facing a challenge understanding where I went wrong in my code. My goal is to display the initial array values in the table data, but so far, I haven't had much success. Here is the HTML section of the code; <body ng-controller ...

Regular expression for parsing any CSS font properties

Does anyone have a reliable regex to break down a css font string into its individual components? 12px arial italic bold sans-serif 12px/50px verdana etc ...