Invoking a TypeScript function using a dynamically named variable

Currently, I am developing an Ionic2 app and encountered a situation where I need to call a function from a Page. I was wondering if it is possible to use a variable name in the function call. For example:

Original code:

this._userDataService.getGrandQuestionsFromServer(this.passedId, newLevel)

Expected code:

this._userDataService.get`${this.questionModuleName}`QuestionsFromServer(this.passedId, newLevel) 

Answer №1

To implement this functionality, you can utilize bracket notation. Here is an example that demonstrates how to do so:

const obj = {
  foobar(arg) {
    console.log(arg);
  }
};

const bar = "bar";
obj[`foo${bar}`]("It works!");

Try incorporating the following line of code into your script:

this._userDataService[`get${this.questionModuleName}QuestionsFromServer`](this.passedId, newLevel)

Answer №2

Discover the amazing feature known as Tagged template literals

Taking template literals to the next level, tagged template literals provide a way to parse them using a function. The first argument of the tag function holds an array of string values, while the subsequent arguments are tied to the expressions within the template literal. Your function has the power to manipulate the string and return it in any format you desire (as shown in the following example). You have the freedom to name your tag function however you like. MDN - Template strings

This powerful feature can be utilized to preprocess the string and generate the desired function call.

Answer №3

Absolutely, here's an example for you:

class TaskManager {
  executeTask(type:string) {
    this[`perform${type}`](type);
  }

  performAction(type: string) {
    console.log(type);
  }
}

let taskManager = new TaskManager();
taskManager.executeTask('Action');

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

acquiring the main class instance within a function without relying on an arrow function

Within my Angular project, I have integrated a datatable with row grouping and row callbacks. Datatable Options openPositionDatatableOptions = { sDom: 'rt<"bottom"p>', ajax: (data, callback, settings) => { this.service.ge ...

Project encapsulating Angular 2 Functionality

I am tasked with creating an angular 2 application that acts as a wrapper for multiple other angular 2 applications. Let's call the main module of the project MainModule. There are also third-party modules such as AppModule1, AppModule2, etc., which ...

What is the best way to integrate Vuex store within the router of a Vue 3 SSR application?

Currently, I am working on a Vue3 project with SSR, Vue-Cli, Vuex, and Typescript. While trying to commit data to the Vuex Store from the router page, I faced an issue. In a .vue file, it's straightforward as I can use this.$store with the typings in ...

I am unable to import choices.js using the "import" command in TypeScript

I'm having trouble importing choices.js using the "import" command: import Choices from 'choices.js'; TS2307: Cannot find module 'choices.js' The following attempts didn't work either: import Choices from '../../node_ ...

Anticipate the resolution of the observable

For the past few months, I have been immersed in a project that required me to work within a synchronous environment without the need for HTTP requests or other external asynchronous access. However, the scope of the project has now changed, and I find mys ...

How can I configure Material-UI's textfield to return a numerical value instead of a string when the type is set to "number"?

Utilizing Material-UI's TextField alongside react-hook-form to monitor inputs has raised an issue for me. I have observed that regardless of the input type, it always returns a string. This creates conflicts with the data types I am using in my codeba ...

Develop a cutting-edge Drag and Drop Functionality using the innovative Material CDK

Here is a unique link you can check out: https://stackblitz.com/angular/nabbkobrxrn?file=src/app/cdk-drag-drop-enter-predicate-example.ts. In this example, I have specific goals: I want to be able to select only one number from the "Available numbers" l ...

The Mat-Card inside the Mat-Table fails to expand to its full width when using overflow-x property

When I inserted a mat-card in a mat-table and set the width to 100%, I noticed that when scrolling with overflow-x from left to right, the whole wrapper was not completely filled with the mat-card. Can anyone suggest CSS optimizations for this issue? Here ...

Having conflicting useEffects?

I often encounter this problem. When I chain useEffects to trigger after state changes, some of the useEffects in the chain have overlapping dependencies that cause them both to be triggered simultaneously instead of sequentially following a state change. ...

Uninitialized variables in Angular 4.0 causing Rxjs issues

Since the update to angular 4.0, I've been encountering errors with RxJs variables. While everything builds without any issues, when I try to load the page, I receive this error message: ERROR Error: Uncaught (in promise): TypeError: Cannot read pr ...

Using Angular2+ with NgbDatePicker requires a specific ControlValueAccessor implementation for Date ngModel

Recently, I was working on developing custom wrappers for the ng-bootstrap library. The specific component I was focused on involves creating a component that accepts a Date object as its [ngModel]. However, during implementation in an application where m ...

Create multiple instances of a component in a dropdown menu using different datasets in Angular 5

Outlined below is the structure of my drop-down list: Companies > Depots Each company has multiple depots. I have developed a component for companies, and upon clicking on a company (menu item), an HTTP request is made to bring all companies which are ...

Passport.js consistently returns an unauthorized status for every request, even when a valid token is provided, or it author

I am facing issues with my Passport.js functions not authenticating users properly. When I use the current form, it always returns "unauthorized" for all requests: import passport from 'passport' import passportJWT from 'passport-jwt' ...

Ways to deduce or implement intellisense for parameter types in overloaded functions

Currently, I am developing an Electron application where numerous events are being passed around with specific listeners assigned to each event. One example is BrowserWindow.on: Electron.BrowserWindow.on(event, listener) The event can take on values such ...

How do I choose the specific financial date of April 1st in the datepicker selection?

I am trying to set the minimum date as 1st April 2018 and the maximum date as the current date. These are the methods I have already attempted: $("#primarySaleDatePicker").pickadate({ min: new Date(2018, 3, 1), max: 'today', ...

Hey there world! I seem to be stuck at the Loading screen while trying to use Angular

A discrepancy in the browsers log indicates node_modules/angular2/platform/browser.d.ts(78,90): error TS2314: Generic type 'Promise' is missing 2 type arguments. ...

Categorizing the types of dynamically retrieved object values

I've developed a unique class with two properties that store arrays of tuples containing numbers. Additionally, I've implemented a method called "getIndex" which dynamically accesses these properties and checks for duplicate number values within ...

Checking that an object's keys are all present in an array in TypeScript should be a top priority

I am working with a const object that is used to simulate enums. My goal is to extract the keys from this object and store them in an array. I want TypeScript to generate an error if any of these keys are missing from the array. // Enum definition. export ...

What are the steps for executing operations on a combined array of different data types?

This code snippet is not functioning as expected type Foo = number[] type Bar = string[] function move(x: Foo | Bar) { const v = x.splice(0, 1) x.splice(1, 0, ...v) } The issue arises because v is inferred to be of type number[] | string[], which ...

Left-to-right animation of Angular Material progress bar buffer

Hey there, I'm interested in creating a progress bar with buffer animation, but the current animation goes from right to left. I'd like it to go from left to right, or have no animation at all. I've searched through the progress bar API, but ...