简体   繁体   English

如何使用外部 scope 中的同名变量解构 Typescript 中的变量?

[英]How to deconstruct a variable in Typescript with a variable of the same name from an outer scope?

I want to use the variable name username and don't know how to do so in the following code:我想使用变量名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 })
  }

My linter complains that { username } is unused:我的 linter 抱怨{ username }未使用:

unused expression, expected an assignment or function call (no-unused-expression)tslint(1)未使用的表达式,需要赋值或 function 调用 (no-unused-expression)tslint(1)

Iss there a propper way to do this if I want to only use username everywhere?如果我只想在任何地方使用username ,是否有适当的方法来做到这一点?

You need to put the destructuring in parentheses:您需要将解构放在括号中:

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

This is true for JS as well.对于 JS 也是如此。 If you were declaring (with let , const , etc) while destructuring, you wouldn't need the parentheses.如果您在解构时声明(使用letconst等),则不需要括号。

More details 更多细节

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM