【问题标题】:Handling non null assertions in react native application在反应本机应用程序中处理非空断言
【发布时间】:2020-08-04 11:54:08
【问题描述】:

我的 react 本机应用程序中有 authContexttoken 属性,它可以是 string | null
我有一些受保护的路线,这意味着除非用户登录并且存在令牌,否则我不会显示链接。
在这条路线上,我试图使用这个令牌,但 TypeScript 说它可能为空,这是有道理的,但我知道它不能。
我知道我可以使用非断言运算符token!,但是有没有替代这个问题的方法,因为它在我的代码中经常发生,并且似乎应该有更好的方法来解决这个问题。感谢您对此的任何想法,谢谢。

【问题讨论】:

    标签: typescript react-native react-navigation


    【解决方案1】:

    一些可以帮助的事情

    1. 使用条件块:
    if (!authContext.token) {
      return null
    }
    // anything after this is going to have TS infer that authContext.token exists 
    
    1. 您提到的非空断言运算符:
    console.log(authContext.token!) 
    
    1. 重新声明变量并输入这个
    const token = (authContext as {token: string}).token
    // use token everywhere in this context instead of authContext.token
    

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 2020-03-05
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 2018-01-15
      • 2015-11-22
      • 2016-11-27
      相关资源
      最近更新 更多