I want to create a generic function that accepts an async function, executes it and catches the error if the provided function encounters any problems.
since I come from a javascript background, I was able to create the following function that does just that. but I wanted to improve it using generics and failed to do so
this code works as expected. but i don't get any type on my 'msg' argument.
const botAsyncHandler = (fn:Function) => (msg: any) => {
Promise.resolve(fn(msg)).catch(error => {
console.log(error.message);
});
};
so i tried to write the following
const botAsyncHandler = <T extends any>(fn:Function)=> (msg: T) => {
Promise.resolve(fn(msg)).catch(error => {
console.log(error.message);
console.log('here');
});
};
sadly my code does not work, and IDE still tells me that msg is of type any implicitly on the following code
bot.on('photo', botAsyncHandler(async msg => {}))
( returns : Parameter 'msg' implicitly has an 'any' type.)
but highlighting the botAsyncHandler shows the following:
botAsyncHandler<TelegramBot.Message>(fn: Function): (msg: TelegramBot.Message) => void
Which seems like what I want. I curious to know where I'm going wrong
fnisasync, there's no point toPromise.resolve(fn(arg)). If you don't knowfnisasync(e.g., it may or may not be), you won't catch errors from it that way if it's synchronous.