javascript - 如何使用外部作用域中的同名变量解构 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
任何地方使用,有没有合适的方法来做到这一点?
解决方案
您需要将解构放在括号中:
({ username } = await this.getUsernameAndDate(email, password));
对于 JS 也是如此。如果您在解构时声明(使用let
、const
等),则不需要括号。
推荐阅读
- asp.net-core - .net Core **Never to Invoke**“next.Invoke after response has been sent to the client”那么如何实现符合良好实践的代码?
- google-cloud-platform - 在项目中查找与 GCP 服务帐号相关联的资源
- r - 如何在r中保持下三角形加对角线
- artifactory - 神器创造柯南频道
- swift - 使用 ArgumentParser 的 Swift 命令行应用程序
- amazon-web-services - 使用实例配置文件时如何在 AWS CLI 中设置配置文件名称
- java - 如何在 Graphics2D Java 中设置文本边界?
- google-assistant-sdk - 获取不成功的 webhook 调用:无法将 JSON 转换为 @assistant/conversation 中表的 ExecuteHttpResponse
- python - 为什么我的 python 程序没有启动 pygame?
- plugins - 如何构建一个 grafana 面板插件?