由于 TypeScript 中的参数,如何键入在另一个函数中收到的回调函数

How to type a callback function received in another function in reason of it's arguments in TypeScript

提问人:Rafael Furtado 提问时间:1/6/2023 更新时间:1/6/2023 访问量:24

问:

好吧,所以,也许问题的标题不太直观,但我不知道该怎么问。

我的问题是,我有一个函数接收回调函数作为它的参数之一,并将参数传递给此回调,接收回调函数的函数将调用收到的回调函数的 .call 方法并返回它的返回值。

我想知道是否可以键入它而不是使用任何,就像下面的示例一样:

我的实际功能是怎样的

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#returntypetype https://www.typescriptlang.org/docs/handbook/utility-types.html#parameterstype

TypeScript 泛型回 typescript-generics

评论


答:

2赞 katniss 1/6/2023 #1

定义一个限制为 (即,必须满足类型) 的泛型参数。然后,您将能够使用找到的实用程序类型:F(...args: any[]) => anyF(...args: any[]) => any

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

评论

0赞 Rafael Furtado 1/6/2023
这正是我所期望的,谢谢!❤