首页 > 解决方案 > 如何使用外部作用域中的同名变量解构 Typescript 中的变量?

问题描述

我想使用变量名username,但不知道如何在以下代码中使用:

  myFunction = async (email: string, password?: string): Promise<boolean> => {
    let username
    if (password) {
      { username } = await this.getUsernameAndDate(email, password)
    } else {
      username = await this.getUsernameByEmail({ email })
    }
    return this.sendUsername({ username })
  }

我的 linter 抱怨{ username }未使用:

未使用的表达式,期望赋值或函数调用 (no-unused-expression)tslint(1)

如果我只想在username任何地方使用,有没有合适的方法来做到这一点?

标签: javascripttypescript

解决方案


您需要将解构放在括号中:

({ username } = await this.getUsernameAndDate(email, password));

对于 JS 也是如此。如果您在解构时声明(使用letconst等),则不需要括号。

更多细节


推荐阅读