Vue3监听click事件时出现TypeScript类型不兼容错误咨询
Vue3+TypeScript事件绑定类型错误原因分析
组件代码
<h2 @click="handleEvent(post.id)">{{ post.title }}</h2> function handleEvent(id: number) { router.push("/post/" + id); }
触发的TypeScript错误
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>'
错误原因
- Vue模板的事件绑定逻辑中,直接写
@click="handleEvent(post.id)"时,会被自动包装成一个匿名箭头函数,等价于:@click="($event) => handleEvent(post.id)" - Vue的点击事件处理函数,默认要求符合
(event: MouseEvent) => void的类型(也可以是不接收参数的函数)。 - 你定义的
handleEvent仅接受number类型参数,此时自动生成的匿名函数类型,和Vue期望的事件处理函数类型不匹配,TypeScript因此抛出类型不兼容的错误。
内容的提问来源于stack exchange,提问作者Dmitrii Mikhaltsov
相关产品推荐
相关产品推荐

