Alexander Knyazev
Alexander Knyazev

Reputation: 2892

How to declare function which returns type of function which is passed as an argument in Typescript?

I have a class method function which is a function for decoration of some function. I need to declare returning value of this function as "Return value is a return value of function which is provided as a parameter"

How can I do it to save typization?

  function operation(): number {
    return 2
  }

  const a = ManagerOfOperations.execute(operation)
  public execute(operationBodyFunction: () => unknown): ReturnType<typeof operationBodyFunction> {
    let functionResult
    try {
      functionResult = operationBodyFunction()
    } catch (error) {
      const operationError: OperationError = {
        originalError: error,
        managerName: this.name,
      }
      throw new Error(JSON.stringify(snapError))
    }

    return functionResult
  }

When I use method from outside, I always have return value of execute method as unknow, but, for example, in this case, I expect number

I tried to use generics here, but my attempts have failed.

Upvotes: 1

Views: 76

Answers (1)

nick zoum
nick zoum

Reputation: 7285

You can do this using generics in 3 simple steps:

  1. Add <T> after the function name(you can change T to whatever name you want to)
  2. State that the return type of the parameter is of type T
  3. State that the return type of the function is of type T
public execute<T>(operationBodyFunction: () => T): T {
    return operationBodyFunction();
}

You can call the function like this execute(() => 0), in this example your IDE should realize that T is of type number.
You can also state the type using execute<{}>(() => ({})).

JSDoc would look like this:

/**
 * @param {() => T} operationBodyFunction
 * @template {T}
 * @returns {T}
 */
function execute<T>(operationBodyFunction: () => T): T;

Upvotes: 1

Related Questions