首页 > 解决方案 > Variable 'newData' is used before being assigned - TypeScript

问题描述

I am getting error in the below implementation of typescript code. I am mapping here one type to another. But vscode shows error that variable 'newData' is used before being assigned. I know it may be a silly error, but I am unable to find it.

onKeyUp(value: string) {
console.log(value);
var link = ``
link = `${API}/${value}`
this.hn.getNews().subscribe(data => {
  this.loading = false;
  var newData:NewsItem[];
  fetch(link)
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    for (var i = 0; i < myJson.length; i++) {
      newData.push(myJson[i])
    }
  })
  this.news = newData;
});
}
}

标签: node.jsangulartypescript

解决方案


您需要将其初始化为空数组,如下所示,

var newData:NewsItem[] = [];

推荐阅读