错误TS2339:JavaScript到Typescript错误

时间:2018-03-29 12:14:47

标签: javascript angular typescript syntax-error

  

src / app / dashboard.component.ts(49,15)中的错误:错误TS2339:属性   '风格'类型'元素'上不存在。   src / app / dashboard.component.ts(50,16):错误TS2339:属性   '的textContent'类型' EventTarget'。

上不存在

这可以作为一个javascript函数,但上面是我尝试在打字稿中使用它时得到的错误。我已经尝试更改var以允许和添加。还有其他建议吗?感谢。

dashboard.ts

var w = document.getElementById('wrapper');
var button = document.getElementById('randomize');
var image = w.children; // inner elements, your quotes divs

// a function to hide all divs
var hideDivs = function(divs) {
  for (var div of divs) {
    div.style.display = 'none';
  }
}

hideDivs(image); // hide all initially

// on click
button.addEventListener('click', function(event) {
  var rnd = Math.floor(Math.random() * image.length); // get random index
  hideDivs(image); // hide all quotes
  image[rnd].style.display = 'block'; // show random quote
  event.target.textContent = 'Click one more time!'; // set button text. event.target is the button you've clicked
})

dashboard.html

  <div id="wrapper">
  <div class="image" img scr='../../assets/mood.jpg'></div>
  <div class="image" img scr='../../assets/mood.jpg'></div>
  <div class="image" img scr='../../assets/mood.jpg'></div>
  <div class="image" img scr='../../assets/mood.jpg'></div>
  <div class="image" img scr='../../assets/mood.jpg'></div>
</div>
<button id='randomize'>Next</button>

1 个答案:

答案 0 :(得分:3)

问题是target的输入为EventTarget,而image的{​​{1}}元素的输入为HTMLCollection。您要访问的两个属性都在Element上定义。你能做的最简单的事情就是使用一个类型断言告诉编译器在你的情况下这两个都是HTMLElement

HTMLElement

哟也可能也想正确输入// on click button.addEventListener('click', function (event) { var rnd = Math.floor(Math.random() * image.length); // get random index hideDivs(image); // hide all quotes (image[rnd] as HTMLElement).style.display = 'block'; // show random quote (event.target as HTMLElement).textContent = 'Click one more time!'; // set button tqext. event.target is the button you've clicked })

hideDivs