本文介绍了Typescript,JSON.parse错误:“类型'null'无法分配给类型'string'."的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里发生了错误:

let moonPortfolio;
...
moonPortfolio = JSON.parse(localStorage.getItem('moonPortfolio'));

我发现此答案,这很有意义,但是在此重构之后,我仍然遇到该错误:

I found this answer which makes sense, however I'm still getting that error after this refactor:

if (portfolio.length === 0) {
  const storedPortfolio = localStorage.getItem('moonPortfolio');

  if (typeof storedPortfolio === 'string') {
    moonPortfolio = JSON.parse(localStorage.getItem('moonPortfolio'));
  }
  else {
    moonPortfolio = [];
  }

  if (moonPortfolio) {
    const savedPortfolio = Object.values(moonPortfolio);
    this.props.fetchAllAssets();
    // this.props.addCoins(savedPortfolio);
  }
}

我首先将localStorage moonPortfolio的结果设置为var,然后检查var是否为typeof字符串.还能得到打字稿错误吗?

I first set the results of localStorage moonPortfolio to a var, then check if the var is typeof string. Yet still getting the typescript error?

这里有什么想法或方向吗?

Any thoughts or direction here?

推荐答案

编译器对localStorage.getItem的内部工作方式不了解太多,也没有假设返回值与某值相同调用getItem到下一个.因此,它只是告诉您,不能确定在第二次调用getItem时结果不是 null.

The compiler doesn't know too much about the inner workings of localStorage.getItem and doesn't make the assumption that the return value will be the same from one call of getItem to the next. So it just tells you that it can't be certain that on the second call to getItem the result isn't null.

尝试简单地传入已创建的变量,而不是再次从localStorage读取:

Try simply passing in the variable you've already created instead of reading from localStorage again:

if (typeof storedPortfolio === 'string') {
  moonPortfolio = JSON.parse(storedPortfolio);
}

这篇关于Typescript,JSON.parse错误:“类型'null'无法分配给类型'string'."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 06:43