我想创建一个接受异步函数的通用函数,执行它并在提供的函数遇到任何问题时捕获错误。
因为我来自javascript背景,所以我能够创建以下功能。但我想用泛型来改进它,却没有这样做
此代码按预期工作。但我的'msg'论点没有任何类型。
const botAsyncHandler = (fn:Function) => (msg: any) => {
Promise.resolve(fn(msg)).catch(error => {
console.log(error.message);
});
};
所以我试着写下面的内容
const botAsyncHandler = <T extends any>(fn:Function)=> (msg: T) => {
Promise.resolve(fn(msg)).catch(error => {
console.log(error.message);
console.log('here');
});
};
遗憾的是我的代码不起作用,IDE仍然告诉我msg在下面的代码中是隐含的类型
bot.on('photo', botAsyncHandler(async msg => {}))
(返回:Parameter 'msg' implicitly has an 'any' type.
)
但突出显示botAsyncHandler
显示以下内容:
botAsyncHandler<TelegramBot.Message>(fn: Function): (msg: TelegramBot.Message) => void
这似乎是我想要的。我很想知道我哪里出错了
Function
类型是没用的。不要使用它。 fn
参数的类型类似于:(msg: T) => Promise<void>
。或者您可以决定接受返回void
:(msg: T) => void | Promise<void>
的同步函数。
你可以写:
const botAsyncHandler = <T>(fn: (msg: T) => void | Promise<void>) => async (msg: T) => {
try {
await fn(msg);
} catch (err) {
console.log(err.message);
}
};
const onString = (msg: string) => {};
const fn = botAsyncHandler(onString);
// Here, the type of 'fn' is: '(msg: string) => Promise<void>'
我无法测试,但您的代码应该按预期工作:
bot.on('photo', botAsyncHandler(async msg => {}))
从您的示例用法:
bot.on('photo', botAsyncHandler(async msg => {}))
和JavaScript的例子一样,看起来你正在尝试创建一个函数来返回一个函数,当调用它时会调用原始函数但是从中处理错误。最简单的方法就是用async
/ try
写一个catch
函数。 JavaScript版本:
const botAsyncHandler = (fn) => async (msg) => {
try {
await fn(msg);
} catch (error) {
console.log(error.message);
}
};
添加类型注释w /泛型:
type AsyncHandler<T> = (arg: T) => {};
const botAsyncHandler = <T extends any>(fn: AsyncHandler<T>) => async (msg: T) => {
try {
await fn(msg);
} catch (error) {
console.log(error.message);
}
};
假设函数必须声明一个形式参数。 Live on the playground。
但是我不确定添加一个类型参数会在这里购买任何东西,因为你使用的是<T extends any>
。