Typescript,JSON.parse错误:“类型'null'无法分配给类型'string'." [英] Typescript, JSON.parse error: "Type 'null' is not assignable to type 'string'."

查看:1172
本文介绍了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:

如错误所述,localStorage.getItem()可以返回字符串或null. JSON.parse()需要一个字符串,因此在尝试使用它之前,您应该测试localStorage.getItem()的结果.

As the error says, localStorage.getItem() can return either a string or null. JSON.parse() requires a string, so you should test the result of localStorage.getItem() before you try to use it.

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'."的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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