Angular TS2345报错:'string | null'无法赋值给'string'类型如何解决
错误原因
该TS2345错误由TypeScript静态类型检查触发:
localStorage.getItem('user')的返回类型为string | null(当localStorage中不存在user键时返回null),但JSON.parse()要求入参必须为string类型,二者类型不匹配导致编译不通过。
解决方法
你可以根据实际场景选择以下任意一种方案:
方案1:空值兜底简化写法
给getItem的返回值加兜底空对象字符串,适配后续原有逻辑:var currentUser = JSON.parse(localStorage.getItem('user') || '{}');当
getItem返回null时,默认传入空对象字符串'{}'做JSON解析,不会触发解析报错,后续currentUser && currentUser.token的判断逻辑可以完全复用。方案2:先判空再解析(推荐)
先取值判断是否存在,再执行解析操作,完全符合类型校验规则,也避免运行时解析异常:const userStr = localStorage.getItem('user'); const currentUser = userStr ? JSON.parse(userStr) : null;方案3:非空断言(仅适用于100%确认
user键一定存在的场景)
用TypeScript非空断言运算符!告诉编译器该值一定不为空,跳过类型检查:var currentUser = JSON.parse(localStorage.getItem('user')!);注意该写法不会处理
user键不存在的情况,运行时可能抛出JSON解析错误,不推荐常规场景使用。
修改后完整代码示例
constructor(private http: HttpClient, private router: Router,) { //append headers // set token if saved in local storage const userStr = localStorage.getItem('user'); const currentUser = userStr ? JSON.parse(userStr) : null; this.token = currentUser && currentUser.token; if(this.token){ this.user_id = currentUser.user.user_id; } }
内容的提问来源于stack exchange,提问作者mikefolu
相关产品推荐
相关产品推荐

