TS2339:类型“元素"上不存在属性“样式"吗? [英] TS2339: Property 'style' does not exist on type 'Element'?

查看:123
本文介绍了TS2339:类型“元素"上不存在属性“样式"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

ngOnInit() {
const navSlide = () => {
  const burger = document.querySelector('.burger');
  const nav = document.querySelector('.nav-links');
  const navLinks = document.querySelectorAll('.nav-links li');
  burger.addEventListener('click', () => {
    nav.classList.toggle('nav-active');
  });
  navLinks.forEach((link, index) => {
  link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.3}s`;
   });
};
navSlide();

}

编译时出现错误:

Property 'style' does not exist on type 'Element'.ts(2339)

我该如何解决?

推荐答案

querySelectorAll 返回已知包含 Element NodeList ,但不包含特别是 HTMLElement s.在您的情况下,您知道这些是 HTMLElements (特别是 HTMLLIElement s),因此您可以使用类型断言来表示:

querySelectorAll returns a NodeList know to contain Elements, but not specifically HTMLElements. In your case, you know that these are HTMLElements (specifically HTMLLIElements), so you can use a type assertion saying that:

navLinks.forEach((link, index) => {
    (link as HTMLElement).style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.3}s`;
});

但请参见 Mike S.评论-我不使用Angular,但听起来这里有更多针对Angular的解决方案.

But see Mike S.'s comment - I don't do Angular, but it sounds like there's a more Angular-specific solution here.

这篇关于TS2339:类型“元素"上不存在属性“样式"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆