I have a function whose only logic is to execute a function that is passed in.
const funcRunner = async (func: Function) => {
return await func()
}
I know that whatever the response of the function that is passed in will be the response of this same function.
However, this function return signature is inferred as Promise<any>
. Is there any way to keep the response type of the original function?
const bool = async isExample(): Promise<boolean> => true;
// result should be boolean, not any
const result = await funcRunner(isExample);
You can define a generic type to run function:
type Runnable<T> = () => Promise<T>;
And then apply it for your funcRunner
async function funcRunner<T>(runnable: Runnable<T>): Promise<T> {
return await runnable();
}
Optionally you can use inline typing:
async function funcRunner<T>(runnable: () => Promise<T>): Promise<T> {
return await runnable();
}
Example usage:
async function example1(): Promise<number> {
return 1;
}
funcRunner(example1)
.then((result: number) => console.log(result))