Selecting the best approach to use based on the argument at hand

The issue at hand

I am facing a challenge with a method foo(msg: string, arg: string). This method calls another method from the object bar, located within the same class as foo. The specific method to be called is determined by the value of arg. I am looking for a suitable solution to tackle this problem effectively.

In my actual codebase, I plan to use this for refactoring purposes. The snippet looks like this:

add() { foo('Adding', 'add'); }
sub() { foo('Subtracting', 'sub'); }
mul() { foo('Multiplying', 'mul'); }
div() { foo('Dividing', 'div'); }

My proposed solution

My current approach involves a method structured like this:

foo(msg: string, arg: string) {
    console.log(msg);
    this.bar[arg]();
    // Additional code here
}

In essence, I aim to invoke the method indicated by arg on bar. This implementation functions correctly. However, I wish to constrain the possible values that arg can assume. One potential strategy could be:

foo(arg: string) {
    if(arg !== 'fun1' && arg !== 'fun2') {
        // Manage error scenario
    }

    this.bar[arg]();
}

The argument arg will always be static. I directly specify constant values every time, such as

foo('fun1');

and never utilize something akin to

// Demonstrative usage I want to avoid
let arg = someFunctionReturningAString();
foo(arg);

My concerns primarily revolve around 1) ensuring robustness and avoiding criticism for adopting unsound practices, and 2) facilitating spelling error detection by IDE tools through a more optimal approach.

Hence, my objective revolves around devising a user-friendly mechanism for invoking a method from bar based on the parameter arg. Ideally, this would enable improved spell-checking capabilities within an IDE. How should I proceed?

Answer №1

In your function signature, you have the option to use literal types such as:

foo(msg: string, arg: 'add' | 'sub' | 'mul' | 'div') {
    console.log(msg);
    this.bar[arg]();
    // Additional code here
}

For more information on literal types in TypeScript, visit https://www.typescriptlang.org/docs/handbook/literal-types.html

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

Implementing a feature to insert a horizontal rule button in React Draft Wysiwyg

I am currently working on implementing a custom button in React Draft Wysiwyg that will allow me to add an <hr> tag to my content. Although I have followed the demos and documentation, I have encountered an issue where the custom button successfully ...

Issue with asynchronous population in Mongoose: Incorrect method invocation causing errors

I have been experimenting with populations in mongoose recently. The original example provided was not working as expected. It kept throwing the error: TypeError: Cannot read property 'name' of undefined at Promise.<anonymous> (/home/kevin ...

Struggling to make Typescript recognize the css prop (emotion) when styling Material-UI components

I'm on a mission to set up a Typescript project with Material-UI v4.11.4 and implement emotion for styling in anticipation of the MUI v5 release. The aim is to integrate emotion into the project so developers can transition to using the new styling in ...

Integrate Thymeleaf properties seamlessly into JavaScript code

I am attempting to embed a property from Spring's application.properties into JavaScript. It is working properly with the following code: <h1 th:utext="${@environment.getProperty('key')}"></h1> However, it returns null with th ...

Generate fresh input fields with distinct identifiers using JavaScript

My challenge is to dynamically create new empty text boxes in JavaScript, each with a unique name, while retaining the text entered in the previous box. I struggled with this for a while and eventually resorted to using PHP, but this resulted in unnecessar ...

Webpack can generate separate compiled files in addition to the bundle

Currently, I am utilizing the webpack loader ts-loader to convert typescript source files into a javascript bundle. My goal now is to not only save the compiled javascript bundle but also the individual compiled javascript files. While I have experience ...

Access the .net web api from a different computer

Currently, I am working on a project that requires me to create a REST API for clients. This API will retrieve data from a database and return it in JSON format. Below is the code for my controller: [Models.AllowCors] public HttpResponseMessage Ge ...

Firebug is indicating that the JavaScript is loading correctly from static files, but unfortunately it is not functioning as expected within the Django framework

After successfully loading the required js files for my template, I am facing an issue where the html elements are not being targeted by the javascript. Strangely, when I include the JS directly in the html file, it works perfectly fine. Can someone explai ...

RTK Query Redux Toolkit: Troubleshooting Cross-Origin Resource Sharing

I am currently attempting to retrieve data from the public Deezer API which can be found here: . To access this data, I am utilizing RTK-Query from Redux Toolkit in the following manner (to then integrate it into my components using hooks obtained from ea ...

I have a task to execute an Ajax request to retrieve and display data from my database table. My approach involves utilizing Perl CGI and attempting to invoke a Perl script using JavaScript

Encountering an issue in the web console with an error in the document.ready function showing an uncaught syntax error unidentified identifier. This CGI script contains JavaScript that calls a Perl script (TestAj.pl) which returns JSON data. I'm atte ...

The Backbone Model is producing unspecified data

Having crafted a backbone model, it looks like this: var note_model = Backbone.Model.extend({ default : { HistoryKey : "", InsertDate : "", MemberKey : "", NoteDate : "", ContactNote : "", User ...

Converting a multi-dimensional array from PHP to JavaScript in a way that cannot be accessed using

I have been working on passing a multidimensional array from PHP (with dynamically inserted values in a real scenario) to JavaScript. However, I am facing an issue where the values are not being printed when using a loop. Upon checking, the array[0].length ...

The child division was not dynamically included

My HTML code currently looks like this: <div class="horizontal-double-large pink" data-title="health" data-legend-one="medical" data-legend-two="natural"> <div class="horizontal-double-element" data-name="India" data-one="40" data- ...

Meshes that overlap with transparency features

Could anyone help me with this issue I'm facing? I have a scenario where I am rendering multiple meshes in Three.JS with different solid colors and transparency. However, these meshes are overlapping and the colors are blending together in the overlap ...

Utilizing API data to set the state in a React component

In my quest to modify the state of this React component, I have a variable called rankAndTeam that holds the "prints=>" data listed below. My goal is to assign "Washington Capitals" to this.state.teamRank["0"], "New York Islanders" to this.state.teamRan ...

Dealing with the challenge of duplicate posts in JqWidgets context menu within a nested grid scenario

I have encountered a double posting issue in the JqWidgets context menu for a nested grid. The event is triggering multiple times (where "n" is the number of times I clicked the context menu). In addition, if I place the event handler method outside the c ...

Navigating to an HTML anchor programmatically within a shiny application

Is it possible to programmatically send the window to #anchor_box when results are available at the end of an observeEvent() with a long running time, instead of relying on the user clicking on a link like a("Go to Results", href = '#anchor_box') ...

Tips for effectively utilizing the Angular ngIf directive for toggling the visibility of elements

<div *ngFor = "let element of myElements, let i=index" [ngClass]="{'selected':element[i] == i}"> <li> Name: {{element.element.name}}</li> <li> Description: {{element.element.description}}</li ...

How to mute a particular warning in development mode with Next.js

Currently in the process of transitioning a CRA app to Next.js in order to enhance SEO. During development, I encountered the following warning: Warning: 'NaN' is an invalid value for the 'left' css style property. I am aware of the s ...

Encountering an issue is common when trying to obtain a list of actors with a specific nationality like Argentine and sorting them by their full name

I am trying to filter actors by their nationality, specifically "Argentine", and sort them by fullName in ascending order. Below is my Actor Routes.js: router.get("/ask/actorsask", actorsCtrl.getActorByNationality); And this is my Actor controller.js e ...