TypeScript is able to automatically deduce the type at runtime

I have a function stored in a variable that I want to pass to another function and have it reuse its parameters. However, this is not working as expected. Take a look at the examples below:

// Attempting to pass a function and steal its parameters dynamically
const a = (a: string) => { }

const b = (...args: Parameters<typeof a>) {
}

const c = (c) => (...args: Parameters<typeof c>) => {
}

const d = <T>(...args: Parameters<T>) => {
}

// This works:
b()

// This does not work; need to find a solution
c(a)()

// This works, but it's not an ideal solution due to its length
d<typeof a>(1)

// In a real-world scenario, the last solution would be something like this
Foo.make<typeof Some.Function.GetIt>(Some.Function.GetIt, ...)

Answer №1

Here is a solution that should suit your needs:

const exampleFunction = (param: string) => { }

const higherOrderFunction = <F extends (...args: any) => any>(func: F) => (...args: Parameters<F>) => {
}

// Using the higher order function with the example function
higherOrderFunction(exampleFunction)("test");

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

(NG2-CHARTS) Unable to connect to the Chart Type as it is not recognized as a valid property for binding

I encountered an issue with my Chart Component where I am seeing the error message below. I have successfully imported ChartsModule into my app.module.ts file, but I am unsure why this error is occurring? Can't bind to 'ChartType' since ...

Set the column span on a particular column within a dynamic table utilizing the mat-table component

I have a dynamic mat-table where columns are created dynamically. I am looking to implement an expand column feature using [attr.colspan]. This functionality should apply the attribute when a click event is detected on a specific column header. When I ins ...

What is the rationale behind Angular 2 and Angular 4's use of banana brackets? Is there a particular reason for this departure from AngularJS's pattern?

Although not directly related to coding, the syntax in AngularJS can still be followed: <input ng-model="hero.name" placeholder="name" type="text"> Here is an example of the syntax used in Angular 2 and its newer versio ...

Struggling with setting up a reducer in TypeScript?

I am currently working through a Microsoft tutorial on using Redux with TypeScript. Although I have been following the steps outlined in the tutorial at https://github.com/Microsoft/TypeScript-React-Starter, I have encountered a problem in the final stage: ...

Removing extensions when auto-importing in IntelliJ is a breeze with these simple steps

As I type something similar to const func = myFuncti..; The suggestion will be for myFunction(), which I confirm. Then, the import statement appears as import {myFunction} from '../myFunction.ts`; I aim to remove the 'ts' extensio ...

I'm experiencing issues with my GAS script when trying to generate events, as it is unable to

Issue After creating a script to generate events from specific emails, the script runs without errors but does not display any events on the calendar. I am confident in the code itself and suspect that there may be authentication settings needing configur ...

Issue: "The specified function type '(num: number) => number' cannot be assigned to type 'number'.(2322)"

Whenever I use a function like this, everything works smoothly: const roundToTwo = (num: number) => { return +(Math.round(+(num + "e+2")) + "e-2"); }; Upon hovering over the function name in VS Code, I can observe that it returns ...

Try querying again if you receive no results from an http.get request in Angular using RXJS Operators

In my Angular service, I sometimes encounter an issue where I receive an empty array. In such cases, I would like to trigger a fresh query. let request = this.http.post(this.searchlUrl, payload).pipe( retryWhen(errors => errors.pipe(delay(100 ...

Best Practice for Using *ngIf in Angular (HTML / TypeScript)

In the past, I frequently used Angular's *ngIf directive in my HTML pages: <p *ngIf="var === true">Test</p> (for instance) However, there have been instances where I needed to perform multiple checks within the *ngIf directive ...

Using Typescript to extract elements from one array and create a new array

I have a set of elements "inputData" , and it appears as follows : [{code:"11" , name= "test1" , state:"active" , flag:"stat"}, {code:"145" , name= "test2" , state:"inactive" , flag:"pass"}, {code1:"785" , name= "test3" , state:"active" , flag:"stat"}, .. ...

Issue with InversifyJS @multiInject: receiving an error stating "ServiceIdentifier has an ambiguous match"

Having an issue with inversifyJs while trying to implement dependency injection in my TypeScript project. Specifically, when using the @multiInject decorator, I keep receiving the error "Ambiguous match found for serviceIdentifier". I've been referenc ...

JavaScript - Imported function yields varied outcome from module

I have a utility function in my codebase that helps parse URL query parameters, and it is located within my `utils` package. Here is the code snippet for the function: export function urlQueryParamParser(params: URLSearchParams) { const output:any = {}; ...

Surprising property quirks in TypeScript classes

I am developing a TypeScript game and encountered an issue while creating a player class. The error I'm getting is: Property 'playerInformation' does not exist on type 'Player' Here is the code snippet: export default class Player ...

Supply type Parameters<T> to a function with a variable number of arguments

I am interested in utilizing the following function: declare function foo(...args: any): Promise<string>; The function foo is a pre-defined javascript 3rd party API call that can accept a wide range of parameters. The objective is to present a coll ...

Issue with IntelliJ: TypeScript Reference Paths Are Not Relative

I am currently using IntelliJ as my IDE, but I am facing an issue with configuring gulp-typescript to compile my typescript code. The problem arises from the fact that IntelliJ does not treat my reference paths relatively, instead it references them from m ...

Service Registry with TypeScript type safety

Is there a way to implement a type-safe service registry in Typescript? I want a function that can return a specific type based on the argument provided. For example: get("a") should return an object of type ServiceA. get("b") should re ...

Challenges with Angular observables

Struggling to make observables work has been quite the challenge for me lately. My code now resembles a chaotic battleground rather than the organized structure it once was. The dreaded "ERROR TypeError: Cannot read property 'map' of undefined" ...

Encountering the error message "React child is not valid as a Gatsby wrapRootElement" while using TypeScript with Gatsby

I've been exploring ways to implement a theme provider in Gatsby using the wrapRootElement browser API. However, I seem to have hit a roadblock as I keep encountering an error message that says "Objects are not valid as a React child (found: object wi ...

Implementing MouseEvents in Typescript React without having to pass them down to child elements

Is it possible to use Mouse Events on a whole React Element without having to pass it to a child element? I have been passing my handleEvent function to several functional components and now I want to know if it can be done without causing a TypeScript err ...

Typescript: The argument provided, which is of type 'number', cannot be matched to a parameter of type 'string'

Need a solution to remove decimals from a number in TypeScript. I have tried using the parseInt method but encountered the following error: Argument of type 'number' is not assignable to parameter of type 'string' Code: function test ...