在 TypeScript 中向 addEventListener() 传递 Promise?

问题描述 投票:0回答:1

在 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

有办法解决这个错误吗?

typescript svelte sveltekit
1个回答
0
投票

如果你真的想让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);
}

© www.soinside.com 2019 - 2024. All rights reserved.