Resident Zero9999
Resident Zero9999

Reputation: 113

Typescript get Parameters from a dynamic function

I want to get the parameters of a function that is saved in different modules. For example myFunction gets the function I desired, then it should be executed with the correct parameters. However the Parameters line shows the following error: Type 'Function' does not satisfy the constraint

public Execute(module: any, myFunction: Function, params: string){
     type TestArgsType = Parameters<typeof myFunction>;
     myFunction.apply(module, params);
}

Is there any way to use the Parameters with a function passed as a parameter?

Upvotes: 1

Views: 746

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

You can if you make yours generic.

const Execute = <T extends (...args: unknown[]) => unknown>(module: any, myFunction: T, params: string){
     type TestArgsType = Parameters<T>;

or

const Execute = <TestArgsType extends unknown[]>(module: any, myFunction: (...args: T) => unknown, params: string){

You might also consider typing module to be something more precise, or at least unknown - using any defeats the purpose of TypeScript.

Upvotes: 1

Related Questions