【发布时间】:2022-11-17 12:04:18
【问题描述】:
我有这段代码可以在单击链接时创建平滑滚动:
const navLinks = document.querySelectorAll('.nav-item a') as NodeListOf<HTMLAnchorElement>;
navLinks.forEach((link: HTMLAnchorElement) => {
link.addEventListener('click', (e) => {
e.preventDefault();
const target = document.querySelector(link.getAttribute('href'));
if (target) {
target.scrollIntoView({
behavior: 'smooth',
});
}
});
});
Typescript 在我设置target 的行上抛出错误(参见问题文本),特别是在document.querySelector(link.getAttribute('href')); 上
如果我用简单的插值 document.querySelector(`${link.getAttribute('href')}`); 替换该行,那么错误就会消失。无论哪种方式,我的代码都按预期工作,但它开始让我不由自主地抽搐,我无法找出 TS 错误。我错过了什么?
【问题讨论】:
标签: typescript