欢迎光临散文网 会员登陆 & 注册

TypeScript: Argument of type 'string | null' is not assignable t

2023-09-18 14:30 作者:doubleyong  | 我要投稿

报错:

    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;

注: 是"{}" 一定要加双引号


TypeScript: Argument of type 'string | null' is not assignable t的评论 (共 条)

分享到微博请遵守国家法律