Reputation: 2892
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
Reputation: 7285
You can do this using generics in 3 simple steps:
<T>
after the function name(you can change T
to whatever name you want to)T
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