javascript - 打字稿 - 对象的条件属性
问题描述
我有以下对象,我希望有一个条件属性:
{ name: this.username, DOB: new Date(this.inputDate)}
比如说,如果用户指定了他们的性别,我希望添加第三个属性,称为性别。以下内容的正确语法是:
{ name: this.username, DOB: new Date(this.inputDate), if(this.userGender) gender: this.userGender}
PS如果没有价值,我不希望在我的对象中拥有该属性。gender
那么,如果条件满足,我怎样才能创建属性呢?
解决方案
理想情况下,您只需在声明对象后添加适当的属性作为第二个操作。所以像:
const myObj = {
name: this.username,
DOB: new Date(this.inputDate),
}
if(this.userGender) myObj.gender = this.userGender;
但是,有时最好声明一个与其余属性内联的“可选”属性,在这种情况下,您可以使用对象扩展来获得您正在寻找的效果:
const myObj = {
name: this.username,
DOB: new Date(this.inputDate),
...this.userGender
? { gender: this.userGender }
: {}
}
推荐阅读
- python-3.x - round() 函数在 apply() 函数中的行为不同
- visual-studio-code - 如何从扩展程序触发 VSCode 中的系统铃声?
- javascript - 为什么我的带有 setTimeout 函数的 requestAnimation 在 Chrome/Opera 中不起作用?
- excel - 如何将 COUNTIFS 与 INDIRECT 结合使用?
- lldb - 如何分页 lldb 调试器帮助文本?
- scala - Spark:数据帧检查点与显式写入磁盘的效率
- shell - 在 shell 脚本中杀死并重新启动 ngrok
- html - 如何根据屏幕尺寸在 Bootstrap 中制作不同高度的部分
- python - 如何在python函数中添加自定义参数参数?
- ios - 除非我先选择不同的行,否则 UIPickerView 不会选择第一行?