I’m struggling with something I’m certain should be simple in Typescript. I’m trying to define a helper function that runs some function and logs a custom message if it errors (this is a simplification of the actual functionality, but it suffices for the example).
async function logIt<T extends () => Promise<any>>(message: string, fn: T): ReturnType<T> {
try {
const result = await fn();
return result;
}
catch (e) {
console.log(message);
throw e;
}
}
I then use it:
class Thing extends Whatever {
// as the name suggests, this function is overwritten from `Whatever` - it's returnType is `Promise<number>`
functionOnWhatever() {
return logIt("hello", () => super.functionOnWhatever());
}
}
The problem is, the logIt
function complains that ReturnType<T>
should be Promise<ReturnType<T>>
– and when I make that change, functionOnWhatever
complains that 'Promise<Promise<number>>' is not assignable to 'Promise<number>'
.