【问题标题】:how to properly annotate object to fix Object is possibly 'null'如何正确注释对象以修复对象可能是“空”
【发布时间】:2020-02-18 03:01:45
【问题描述】:

我收到以下错误:对象可能在 this.auth.currentUser 上为 'null' 我如何正确注释此行以使错误消失?

方法:

doPasswordUpdate = (password: string): Promise<void> =>
    this.auth.currentUser.updatePassword(password)

注释: auth: firebase.auth.Auth

感谢您的帮助Q!

【问题讨论】:

  • google 一下这个错误,有一堆帖子在回答这个问题,比如这个:stackoverflow.com/questions/54884488/…
  • 感谢您的回复。我尝试了一些解决方案,但大多数都不起作用: doPasswordUpdate = (password: string): Promise | void => { if (this.auth) { this.auth.currentUser.updatePassword(password) } } 或 this.auth!.currentUser.updatePassword(password) 它仍然抛出同样的错误
  • 好吧,你必须检查每一步,比如if (this.auth &amp;&amp; this.auth.currentUser &amp;&amp; this.auth.currentUser.updatePassword) { ... },或类似的东西,因为其中任何一个都可能为空。可能不需要检查this,但我不确定。
  • 感谢您的回复!我现在明白我做错了什么;)

标签: reactjs typescript firebase


【解决方案1】:

在这种情况下,您最好执行以下操作:

doPasswordUpdate = (password: string): Promise<void> =>
  this.auth.currentUser  
    ? this.auth.currentUser.updatePassword(password)
    : Promise.resolve()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多