Typescript-对象的Conditional属性



我有以下对象,我希望对其具有条件属性:

{ name: this.username, DOB: new Date(this.inputDate)}

比方说,如果用户指定了他们的性别,我希望添加第三个名为gender的属性。以下内容的正确语法是什么:

{ name: this.username, DOB: new Date(this.inputDate), if(this.userGender) gender: this.userGender}

第页。S.如果对象中没有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 }
}

也可以这样做,更干净可读。

const myObj = {
name: this.username,
DOB: new Date(this.inputDate),
...(this.userGender && { gender : this.userGender })
}

试试这个

let userObj = { name: this.username, DOB: new Date(this.inputDate) }
if(this.userGender) 
userObj["gender"] = this.userGender;

最新更新