You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 19:32:44