Agree with @Bergi about the new function.
Typescript doesn't like it when we return directly the ReturnType
in case of async
method use. I guess it's because I havent specified that ReturnType
must be of type Promise
, but I've found now way how to specify it.
type ReturnType any> = T extends (...args:
any) => infer R ? R : any Obtain the return type of a function type
The return type of an async function or method must be the global
Promise type.(1064)
I've found a turnaround by extracting what's templated inside of the Promise
and redeclaring it.
type ExtractPromiseTemplate<T> = T extends PromiseLike<infer U> ? U : T
function logExceptions<T extends (...args: any[]) => ReturnType<T>>(func: T): (...funcArgs: Parameters<T>) => Promise<ExtractPromiseTemplate<ReturnType<T>>> {
return async (...args: Parameters<T>): Promise<ExtractPromiseTemplate<ReturnType<T>>> => {
try {
console.log('Will call now');
const ret = await func(...args);
return ret as ExtractPromiseTemplate<ReturnType<T>>;
} catch (err) {
console.log(func.name + " caused an error");
throw err;
}
};
}
async function asyncExample() {
throw new Error('Example')
}
logExceptions(asyncExample)();
Call the following code to test the validity of the returned value :
type ExtractPromiseTemplate<T> = T extends PromiseLike<infer U> ? U : T
function logExceptions<T extends (...args: any[]) => ReturnType<T>>(func: T): (...funcArgs: Parameters<T>) => Promise<ExtractPromiseTemplate<ReturnType<T>>> {
return async (...args: Parameters<T>): Promise<ExtractPromiseTemplate<ReturnType<T>>> => {
try {
console.log('Will call now');
const ret = await func(...args);
return ret as Promise<ExtractPromiseTemplate<ReturnType<T>>>;
} catch (err) {
console.log(func.name + " caused an error");
throw err;
}
};
}
async function asyncExample():Promise<string> {
return 'a';
}
(async() => {
const ret = await logExceptions(asyncExample)();
})();
New playground for @bergi comment