我的react本机应用程序中有authContext
,具有token
属性,它可以是string | null
我有一些受保护的路由,这意味着除非用户登录并且存在令牌,否则我不会显示链接
在这条路线上,我试图使用这个令牌,但TypeScript说它可能为null,这是有道理的,但我知道它不能
我知道我可以使用非断言运算符token!
,但有没有其他方法可以解决这个问题,因为它在我的代码中经常发生,似乎应该有更好的方法来解决这个问题。感谢您对此的任何想法。
一些可以帮助的东西
- 使用条件块:
if (!authContext.token) {
return null
}
// anything after this is going to have TS infer that authContext.token exists
- 您提到的非null断言运算符:
console.log(authContext.token!)
- 重新定义变量并键入
const token = (authContext as {token: string}).token
// use token everywhere in this context instead of authContext.token