如何在TypeScript中键入因参数而在另一个函数中接收到的回调函数

t3psigkw  于 2023-01-10  发布在  TypeScript
关注(0)|答案(1)|浏览(126)

好吧,那么,也许这个问题的标题不太直观,但我不知道如何确切地问它。
我的问题是,我有一个函数,它接收一个回调函数作为它的一个参数,以及传递给这个回调函数的参数,而接收回调函数的函数将调用所接收的回调函数的**.call**方法,并返回它的return。
我想知道它是否甚至可以键入它,而不是使用任何,像下面的例子:

我的实际功能是什么

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;  
}

我希望它是什么样的,用泛型

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;
}

使用我想要的通用形式,当有人调用 executeFunction 时,将获得与直接调用回调函数相同的返回类型
在TypeScript文档中,我发现一些实用程序类型可能有助于实现这一点,但我不知道如何实现它:
https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetypehttps://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype

rjee0c15

rjee0c151#

定义一个泛型参数F,它被约束为(...args: any[]) => any(也就是说,F必须满足类型(...args: any[]) => any),然后你就可以使用你找到的实用程序类型了:

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

相关问题