如何让TypeScript对此错误感到满意:
Property 'dataset' does not exist on type 'EventTarget'
当我尝试实现以下代码片段时,我得到了它:
document.addEventListener(
"click",
(event) => {
event.preventDefault();
if (event !== null && event.target !== null) {
const element = event.target as Element;
if (element.matches(".dropdown-item.city")) {
const cityName = event.target.dataset.value;
console.log("City =", cityName);
dropdown.classList.toggle("active");
}
}
},
false
);
发布于 2021-05-20 08:46:51
与断言类型相比,一种选择是检查条件中的元素是否为正确的类型。在这种情况下,我相信您希望确保它是一个instanceof HTMLElement
。
document.addEventListener(
"click",
(event) => {
event.preventDefault();
if (event !== null && event.target instanceof HTMLElement) {
const element = event.target;
if (element.matches(".dropdown-item.city")) {
const cityName = element.dataset.value;
console.log("City =", cityName);
dropdown.classList.toggle("active");
}
}
},
false
);
https://stackoverflow.com/questions/67612502
复制相似问题