在 sveltekit 应用程序上,我尝试创建一个事件侦听器,使用 Typescript 执行异步函数(突变)。
onMount(() => {
document.addEventListener('keyup', handleKeyPress);
});
我传递给 addEventListener 的参数是一个异步函数,定义为...
async function handleKeyPress(event: KeyboardEvent) {
if (mainList.length > 0) {
const press =
event.key === 'ArrowLeft' ? 'left' : event.key === 'ArrowRight' ? 'right' : null;
if (press) {
await moveItem(press);
}
}
}
你看,addEventListener 需要一个返回 void 的函数,所以我收到此错误:
Promise returned in function argument where a void return was expected. eslint
有办法解决这个错误吗?
如果你真的想让eslint开心,你可以这样做:
function handleKeyPress(event: KeyboardEvent) {
async handler(key: string) {
if (mainList.length > 0) {
const press =
key === 'ArrowLeft' ? 'left' : key === 'ArrowRight' ? 'right' : null;
if (press) {
await moveItem(press);
}
}
}
handler(event.key);
}