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

TypeScript中EventTarget用法及event.target.matches等效写法咨询

在TypeScript中使用event.target.matches的正确姿势

嘿,作为TypeScript新手碰到这个问题太正常啦!我来帮你把这个问题理清楚~

首先得明白为什么直接用event.target.matches会报错:TypeScript对DOM元素的类型检查比JavaScript严格很多,event.target的默认类型是EventTarget | null,而matches是Element接口才有的方法,所以TS会提示你找不到这个方法。下面给你两种靠谱的解决方式:

1. 安全的类型守卫写法(推荐)

先通过类型守卫判断event.target是不是Element的实例,这样TypeScript会自动缩小类型范围,同时还能避免null的情况:

window.onclick = function(event) {
  // 先判断目标元素是否是Element实例,再调用matches
  if (event.target instanceof Element && !event.target.matches('.dropbtn')) {
    const dropdowns = document.getElementsByClassName("dropdown-content");
    for (let i = 0; i < dropdowns.length; i++) {
      const openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
};

2. 类型断言写法(简单直接)

如果你能确定event.target一定是一个Element(比如你已经做过null判断),可以用类型断言快速解决:

window.onclick = function(event) {
  if (event.target && !(event.target as Element).matches('.dropbtn')) {
    const dropdowns = document.getElementsByClassName("dropdown-content");
    for (let i = 0; i < dropdowns.length; i++) {
      const openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
};

给你修改后的完整TypeScript代码

顺便把你的示例代码也改成符合TS规范的版本(比如用let代替var,增加null判断):

function myFunction() {
  const dropdown = document.getElementById("myDropdown");
  // 先判断元素是否存在,避免null报错
  if (dropdown) {
    dropdown.classList.toggle("show");
  }
}

// Close the dropdown menu if the user clicks outside of it
window.onclick = function(event) {
  if (event.target instanceof Element && !event.target.matches('.dropbtn')) {
    const dropdowns = document.getElementsByClassName("dropdown-content");
    for (let i = 0; i < dropdowns.length; i++) {
      const openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
};

小提示:TypeScript里尽量多用类型守卫而不是强制断言,这样代码会更安全,也更符合TS的类型检查理念哦~

内容的提问来源于stack exchange,提问作者blazing

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:27:14