在 Vue 3 中侦听事件时,TypeScript 错误“Type '($event: any) => void' is not assignable to type'”

Dmi*_*sov 16 typescript vue.js

组件代码:

<h2 @click="handleEvent(post.id)">{{ post.title }}</h2>

function handleEvent(id: number) {
  router.push("/post/" + id);
}
Run Code Online (Sandbox Code Playgroud)

打字稿错误:

Type '($event: any) => void' is not assignable to type 'MouseEvent'.ts(2322)
__VLS_types.ts(107, 56): The expected type comes from property 'click' which is declared here on type 'EventObject<undefined, "click", {}, MouseEvent | undefined>'
Run Code Online (Sandbox Code Playgroud)

问题是什么?

pus*_*ech 12

据我了解,在这个问题上我们有两个选择:

  1. 添加@types/node: '18.8.0'
  2. 等待此更改合并到 vue 2.7 版本中

注意:不要使用^,将版本修复为18.0.0

我安装了 @types/node 固定版本并为我工作。


小智 3

我们面临同样的问题 - 模板中的所有事件处理程序都是错误的。几天前就出现了。根据打字稿定义,事件处理程序必须返回类型“Event”或“MouseEvent”。因此,我们在模板中更正如下:

<h2 @click="(e : MouseEvent) => {handleEvent(post.id); return e;}">{{ post.title }}</h2>
Run Code Online (Sandbox Code Playgroud)

它有效,但似乎不是应该编写事件处理程序的方式......