Execute a Typescript function where parameters are passed to another function

In my coding project, I came across a situation where I needed to write a method in Typescript. This method should allow me to run some checks and, if those conditions are met, return the result of another method. What I want is to pass a method along with its parameters to another method so that it can be executed under certain conditions.

Initially, I tried doing this by implementing the following code (you can check the fiddle here):

function getTheResult(inputVal:number, multiplier:number, subtractor:number):number{
  inputVal = inputVal * multiplier - subtractor;
  return inputVal;
}

function intermediary(passedFunction:Function, inputVal:number, multiplier:number, subtractor:number, name:string):number{
  if(name == 'John')
    return -1;

  return(passedFunction(inputVal, multiplier, subtractor));
}

console.log(intermediary(getTheResult, 5, 4, 5, 'Mike'));

Although this code works as intended, I wanted to find a way to pass getTheResult(5,4,5) directly to

intermediary(passedFunction:Function, name:string)
. That way, intermediary() can call any method that I pass to it, regardless of the function's parameters. To better understand, you can refer to this fiddle (available here):

function getTheResult1(inputVal:number, multiplier:number, subtractor:number):number{
  inputVal = inputVal * multiplier - subtractor;
  return inputVal;
}

function getTheResult2(inputVal:number, dividor:number):number{
  inputVal = inputVal / dividor;
  return inputVal;
}

function intermediary(passedFunction:Function, name:string):number{
  if(name == 'John')
    return -1;

  return(passedFunction());
}

let myFirstNum:number = intermediary(getTheResult1(2,3,4), 'John');
let mySecondNum:number = intermediary(getTheResult2(2,3), 'Doe');

console.log(myFirstNum);
console.log(mySecondNum);

Can you help me understand how I can achieve this?

Answer №1

The correct solution was given by Riadh Adrani in their comment.

By using the intermediary function, myFirstNum is assigned the value returned by getTheResult1(2,3,4) when this function is invoked as a callback, with 'John' passed as an argument.

This approach effectively resolves the problem by passing the actual callback instead of its result.

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

Type Vue does not contain the specified property

I am encountering an issue where I am using ref to retrieve a value, but I keep receiving the error message "Property 'value' does not exist on type 'Vue'". Below is the code snippet causing the problem: confirmPasswordRules: [ ...

The data type 'string' cannot be assigned to the data type 'Position'

Currently, I am in the process of converting React js to typescript. The component being used is a Class Component. I would like to obtain CSS settings through props and apply them to an element. How can I resolve this issue? render(){return( <span st ...

React-snap causing trouble with Firebase

I'm having trouble loading items from firebase on my homepage and I keep running into an error. Does anyone have any advice on how to fix this? I've been following the instructions on https://github.com/stereobooster/react-snap and here is how ...

Inputting data types as arguments into a personalized hook

I am currently developing a Next.js application and have created a custom hook called useAxios. I am looking to implement a type assertion similar to what can be done with useState. For example: const [foo, setFoo] = useState<string>(''); ...

The provided argument, which is of type 'RefObject<HTMLDivElement>', cannot be assigned to the parameter of type 'IDivPosition'

Currently, I am implementing Typescript with React. To organize my code, I've created a separate file for my custom function called DivPosition.tsx. In this setup, I am utilizing useRef to pass the reference of the div element to my function. However ...

Step-by-step guide to setting up a TypeScript project on Ubuntu 15 using the

As a newcomer to UBUNTU, I have recently ventured into learning AngularJS2. However, when attempting to install typescript using the command: NPM install -g typescript I encountered the following error message: view image description here ...

The Angular service retrieves only the default values

I'm currently following an Angular tutorial and encountering some issues. Problem #1: The problem arises when using two services, recipe.service.ts (handles local data manipulation) and data-storage.service.ts (stores data in Firebase). When the getR ...

The Angular test spy is failing to be invoked

Having trouble setting up my Angular test correctly. The issue seems to be with my spy not functioning as expected. I'm new to Angular and still learning how to write tests. This is for my first Angular app using the latest version of CLI 7.x, which i ...

Creating a structure within a stencil web component

In my current project, I am utilizing Stencil.js (typescript) and need to integrate this selectbox. Below is the code snippet: import { Component, h, JSX, Prop, Element } from '@stencil/core'; import Selectr from 'mobius1-selectr'; @ ...

How to reveal hidden Div element at a specific index with Angular Material table

In my mat-table, there are several functionalities available: 1. The ability to add or remove rows 2. Adding data into a row using different controls such as combo-boxes, text boxes, etc. One of the controls is a text box labeled "Additional Information ...

Typescript's spellbinding courses

I'm encountering some issues with Typescript and the "@botstan/Magic" library in nodejs. Before we proceed, please take a look at the "Magic" documentation. Follow these lines: import Magic from "@botstan/magic"; import * as _ from "lodash"; @ ...

What is the best way to retrieve all the keys from an array?

I am looking to retrieve the address, latitude, and longitude data dynamically: let Orders= [{ pedido: this.listAddress[0].address, lat: this.listAddress[0].lat, lng: this.listAddress[0].lng }] The above code only fetches the first item from the lis ...

Having trouble resolving React within the Formik/dist package due to a custom webpack configuration

Struggling to set up projects from scratch, encountering an issue with webpack not being able to resolve formik's modules while other third-party modules like styled-components work fine. I've tried searching online for a solution but couldn&apos ...

An effective approach to positioning HTML elements at specific X and Y coordinates

I have an innovative project idea! The concept is to enable users to create points by clicking on the display. They can then connect these points by clicking again. However, I am facing a challenge when it comes to creating HTML elements at the exact loc ...

Error encountered during conversion to Typescript for select event and default value

When trying to set the defaultValue in a Select component, TSlint throws an error - Type 'string' is not assignable to type 'ChangeEvent<HTMLInputElement> | undefined - for the code snippet below: const App = () => { const [ mont ...

Listening for Angular 2 router events

How can I detect state changes in Angular 2 router? In Angular 1.x, I used the following event: $rootScope.$on('$stateChangeStart', function(event,toState,toParams,fromState,fromParams, options){ ... }) In Angular 2, using the window.addEv ...

Retrieve information from a URL to transmit to a different page in NextJS using Typescript and AppRouter

I'm struggling with transitioning from the Home page to the Detail page. I've successfully passed data to the URL from the Home screen, but I'm having trouble accessing it in the Detail screen. I'm working with NextJS ver 13, using Type ...

Filtering database results from an Angular component

I am currently working on an Angular component and I have a result variable in the .ts file that stores data retrieved from the database. My goal is to filter this result variable to display only 20 records and sort them by date either in ascending or de ...

When executing the release command in Ionic 3, the Angular AoT build encountered a failure

Struggling to get my Sony Z2 smartphone app running. Command used: ionic build android --prod --release Error displayed in console: typescript error Type CirckelmovementPage in C:/Users/fearcoder/Documents/natuurkundeformules/src/pages/cir ...

Generating output from a callback function in TypeScript

When I execute a graphql query, the showUsers function is supposed to display all users (styled as boxes). However, at the moment, nothing is showing up. I am utilizing a functional component instead of a class component. This function is invoked after m ...