报错信息:Unexpected nullable string value in conditional. Please handle the nullish/empty cases explicitly.eslint@typescript-eslint/strict-boolean-expressions
错误解释:
在TypeScript中,localStorage.getItem("token")
返回的类型可能是 string | null
,因为 getItem
方法可能会返回一个字符串或者 null
。当尝试使用或操作符(||
)来提供一个空字符串作为备选值时,TypeScript 可能会报告一个类型错误,因为它期望得到的是一个 string
类型,但是可能会得到一个 null
。
解决方法:
确保 localStorage.getItem("token")
返回的值是 string
类型。可以通过使用非空断言操作符(!
)或类型断言(as
)来告诉TypeScript 你确信结果不是 null
。
1、使用非空断言操作符(推荐用于确信 token
存在的情况):const token =
localStorage.getItem("token") || ''; // 如果token为null或者undefined,则返回空字符串
2、使用类型断言(当 token
可能不存在时):
const token = (localStorage.getItem("token") as string) || ''; // 告诉TypeScript token一定是string类型
3、使用逻辑与操作符(&&
)来提供默认值(这种方式不会改变 null
的类型):
const token = localStorage.getItem("token") ?? ''; // 当token为null或者undefined时,返回空字符串