Type string | null is not assignable to type string

¥20.00

vue开发的项目,编译发布的时候一直报错:Type 'string | null' is not assignable to type 'string',详细报错如下图:

Type string | null is not assignable to type string


这个该如何才能解决呢,我不是专业的前端,项目实在HBuilder里面发布的。


余光 T0 发布于2年前

最佳解决方案

原因分析

Typescript里面变量初始化时赋值如果和期望的值类型不一样就会报类似Type ‘’ is not assignable to type ‘’ 这样的错误。

你程序里userId:sting = windows.localStorage.getItem('user_id')后面 localStorage返回的值不一定时string类型的,有可能是undefined类型的,就引发这样的错误了。 

可以考虑如下写法:

let userId:string;
if( windows.localStorage.getItem('user_id')!=undefined){
    userId=  windows.localStorage.getItem('user_id');
}


小忆控 T0 被采纳率100%
2021-03-28 17:04
打赏 0 1
页面统计
1711 访问
0 帮助
0.00 打赏

hierror 2019 © hierror.com 京ICP备13026190号-1

通知消息
  • 暂无任何消息