Home > Software engineering >  How to type a callback function received in another function in reason of it's arguments in Typ
How to type a callback function received in another function in reason of it's arguments in Typ

Time:01-06

Ok, so, maybe the title of the question isn't too intuitive, but I don't know how to exactly ask it.

My problem is, I have a function that receives a callback function as one of it's arguments and the arguments to be passed to this callback and the function that receives the callback function will call the .call method of the received callback function and will return it's return.

I want to know if it's is even possible to type it instead of using any, like the exemples bellow:

How my actual function is

public static executeBlockingFunction(callbackFunction: Function,
    callbackArguments: Array<any>): any{
    // execute some code before calling the callback function
    
    const callbackReturn = callbackFunction.call(callbackFunction, ...callbackArguments);

    // executes some more code before returning the callback return
   
    return callbackReturn;  
}

How I want it to be, with generics

public static executeBlockingFunction<maybe some generic here, I don't know>(callbackFunction: <somehow the type of the callback function>,
    callbackArguments: Array<<the actual types of the arguments of the callback function>>): <the return type of the callback function> {
    // execute some code before calling the callback function
    
    const callbackReturn = callbackFunction.call(callbackFunction, ...callbackArguments);

    // executes some more code before returning the callback return
   
    return callbackReturn;
} 

With the generic form that I want, when someone call the executeFunction will get as return the exactly return type as if they calling directly the callback function

In the TypeScript documentation, I found some utilities type that may can help achieve this, but I have no idea on how to implement it:

https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype

CodePudding user response:

Define a generic parameter F that is constrained to (...args: any[]) => any (that is, F must satisfy the type (...args: any[]) => any). Then you'll be able to use the utility types you found:

public static executeBlockingFunction<F extends (...args: any[]) => any>(callbackFunction: F, callbackArguments: Parameters<F>): ReturnType<F> {
  • Related