Svelte中on:click与on:keydown事件的正确类型标注方法
Svelte + TypeScript 点击事件类型定义问题
之前看到有说法称Svelte中on:click事件的处理函数类型应该这样写:
const handleClick = (e: svelte.JSX.MouseEventHandler<HTMLLIElement>) => { console.log(JSON.stringify(e)); };
但实际使用时会触发类型错误,若尝试直接使用MouseEventHandler<HTMLLIElement>,又会遇到该类型无法导入的问题。
正确解决方式
直接使用事件对象类型
对于<li>元素的点击事件,可直接将参数类型定义为MouseEvent<HTMLLIElement>,或简化为MouseEvent:// 精确限定元素类型 const handleClick = (e: MouseEvent<HTMLLIElement>) => { console.log(JSON.stringify(e)); }; // 简化写法 const handleClick = (e: MouseEvent) => { console.log(JSON.stringify(e)); };正确导入
MouseEventHandler类型
若要使用MouseEventHandler类型,需从svelte/JSX模块中导入:import type { MouseEventHandler } from 'svelte/JSX'; const handleClick: MouseEventHandler<HTMLLIElement> = (e) => { console.log(JSON.stringify(e)); };
内容的提问来源于stack exchange,提问作者Peter Toth
相关产品推荐
相关产品推荐

