Improving the structure of a TypeScript switch statement

Looking for a more efficient way to implement a switch statement in TypeScript? Here is the current code snippet from a component:

switch (actionType) {
    case Type.Cancel {
        this.cancel();
        break;
    }
    case Type.Discard {
        this.discard();
        break;
    }
    case Type.Delete {
        this.delete();
        break;
    }
}

I've been exploring the strategy and/or factory pattern as alternatives, but they involve creating different classes for each case. I'm undecided on whether this is the best approach for my situation, so any insights on this topic would be greatly appreciated.

Answer №1

An effective approach is to create a mapping from the Type to corresponding functions:

class Example {
  private functionMap = new Map<Type, () => void>([
    [Type.Cancel, () => this.cancel()],
    [Type.Discard, () => this.discard()],
    [Type.Delete, () => this.delete()]
  ]);

  yourFunction(actionType: Type) {
    if (this.functionMap.has(actionType)) {
      this.functionMap.get(actionType)();
    }
  }
}

If the functions are already bound, you can simplify it as follows:

  private functionMap = new Map<Type, () => void>([
    [Type.Cancel, this.cancel],
    [Type.Discard, this.discard],
    [Type.Delete, this.delete]
  ]);

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

Tips for incorporating a svg file into your React project

I am facing an issue with my custom React, Typescript, and Webpack project. I am trying to import a basic .svg file and utilize it in one of my components. However, Typescript is throwing the following error: Cannot find module I have tried installing s ...

Integrate a service component into another service component by utilizing module exports

After diving into the nestjs docs and exploring hierarchical injection, I found myself struggling to properly implement it within my project. Currently, I have two crucial modules at play. AuthModule is responsible for importing the UserModule, which conta ...

What is the process of creating a for loop in FindById and then sending a response with Mongoose?

Is there a way to get all the data in one go after the for loop is completed and store it in the database? The code currently receives user object id values through req.body. If the server receives 3 id values, it should respond with 3 sets of data to th ...

What are the steps to installing Typescript on my computer?

npm ERROR! encountered code EACCES during installation npm ERROR! while trying to create a directory npm ERROR! at path /usr/local/lib/node_modules/typescript npm ERROR! with error number -13 npm ERROR! Error: EACCES: permission denied, mkdir '/usr/lo ...

The Relationship Between Typing Variables and Generic Types in Functions

I need help implementing a specific function type: type TestType<T extends HTMLElement> = (input: T) => React.Ref<T>; I have a variable that I want to be typed with the above type for strict type guarantees on the return type: const Test ...

When using Webpack and Typescript together with the watch feature, an error with code TS2554 may occur only during

Software in use: webpack 4.8.3 typescript 2.8.3 ts-loader 4.3.0 Configuration for Webpack: rules: [ { test: /\.ts(x?)$/, exclude: /node_modules/, use: ['ng-annotate-loader', 'ts-loader'] }, . ...

Angular Inner Class

As a newcomer to Angular, I have a question about creating nested classes in Angular similar to the .NET class structure. public class BaseResponse<T> { public T Data { get; set; } public int StatusCo ...

I'm on the lookout for a component similar to angular-ui-tree that is compatible with angular

As a new developer, I am in search of a component similar to: But specifically for Angular 6, with all the same functionality (drag-and-drop capability, nested items, JSON structure, etc.). I have come across some components that either lack dragging fun ...

Tips for effectively highlighting search text within HTML content without causing any issues

I am in search of a solution that can assist me in searching for specific terms within an HTML string while also highlighting them. I have the ability to remove the HTML content from the string, but this poses the problem of losing the context of the origi ...

The tsconfig.json file does not support the path specified as "@types"

Having set up multiple absolute paths for my Next.js application, I encounter an issue where importing a component from the absolute path results in something like "../componentName" instead of "@components/componentName" when I am inside another folder. T ...

next.js users may encounter a problem with react-table not rendering correctly

Encountering difficulties while attempting to integrate a basic table function into my upcoming application. Despite being a sample output, the function fails to load into the index for some unknown reason! // Layouts import Layout from "../components ...

Automatically expanding PrimeNG Turbotable rows

I am using a PrimeNg turbotable that has a row expansion feature enabled. I am looking for a way to automatically expand the rows by default when the table loads. Shown below is my code: HTML <p-table [columns]="cols" [value]="cars" dataKey="vin"> ...

Utilizing StyleFunctionProps within JavaScript for Chakra UI Enhancements

I need help figuring out how to implement StyleFunctionProps in my Chakra UI theme for my NextJS project. The documentation on Chakra's website provides an example in Typescript, but I am working with Javascript. Can someone guide me on adapting this ...

Tips for simulating or monitoring an external function without an object using Typescript 2 and Jasmine 2 within an Angular 4 application

In order to verify if a function called haveBeenCalledWith() includes the necessary parameters, I am seeking to validate the correctness of my call without actually executing the real methods. I have experimented with multiple solutions sourced from vario ...

Is there a possibility of a @types/jest version 27 coming out soon?

It appears that all Jest related packages I've come across are currently on version 27, except for this one. I wonder if there's a specific reason for this disparity. The Jest documentation mentions the importance of matching versions with associ ...

Guide on combining two classes as the base class for an extended class in Typescript

Is it possible to create a higher order function (HOF) that modifies or adds a property to the prototype of a given class? interface IStore { new (): {}; } interface IWatchable { new() : { watch: boolean; }; } const Store = <T extends ISt ...

Can you explain the distinction between any[] and [] in TypeScript?

Here is an example that successfully works: protected createGroups(sortedItems: Array<TbpeItem>): any[] { let groups: any[] = []; return groups; } However, the second example encounters a TypeScript error: type any[] not assignable to ...

Tips for choosing a specific quantity and adjusting its value

Just starting out with Ionic 3 and looking for some help with the code. Can anyone assist me in understanding how to change the value of an item in a shopping cart and have the subtotal reflect that change? cart.ts private _values1 = [" 1 ", "2", " 3 "," ...

At first, Typescript generics make an inference but are ultimately specified

In my TypeScript code, I have defined a custom Logger class with specific options. The DefaultLevel type is created as a union of 'info' and 'error'. The LoggerOptions interface includes two generics, CustomLevels and Level, where Custo ...

Type guards do not work properly on a union of enum types in TypeScript

Recently delved into the concept of Type Guards Chapter within the realm of Typescript However, I encountered an issue where my basic type guards failed to differentiate a union of enums. Why is this happening? enum A { COMMA = ',', PLUS = & ...