doubleyong
管理员
管理员
  • 最后登录2024-04-24
  • 发帖数1167
  • 最爱沙发
  • 喜欢达人
  • 原创写手
  • 社区居民
  • 忠实会员
阅读:1711回复:0

[typescript]TypeScript: Argument of type 'string | null' is not assignable to parameter of type 'string'.

楼主#
更多 发布于:2023-09-18 11:21
报错:
    Argument of type 'string | null' is not assignable to parameter of type 'string'.

代码:
 JSON.parse(sessionStorage.getItem("user") ).userId;


原因:sessionStorage.getItem("user")  方法可能返回null , 而null 不是字符串 , 则JSON.parse在执行时就会出错,所以typescript 提示了上面的错误信息,即要处理为null 的情况



解决方案:JSON.parse(sessionStorage.getItem("user") || "{}" ).userId;
知识需要管理,知识需要分享
游客


返回顶部

公众号

公众号