简体   繁体   English

Typescript - 对象的条件属性

[英]Typescript - Conditional property of object

I have the following object to which I wish to have a conditional property: 我有以下对象,我希望有一个条件属性:

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

Say, I wish to add a third property called gender if the user has specified their gender. 比如说,如果用户指定了性别,我希望添加第三个名为gender的属性。 What would the proper syntax for the following be: 以下适当的语法是什么:

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

PS I do not wish to have the gender property in my object if there is no value along with it. PS我希望在我的对象中有gender属性,如果它没有值。 So how can I only create the property if the condition is satisfied? 那么如果条件满足,我怎么才能创建属性呢?

Ideally, you would just add the appropriate property as a second action after declaring your object. 理想情况下,您只需在声明对象后添加适当的属性作为第二个操作。 So something like: 所以类似于:

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

if(this.userGender) myObj.gender = this.userGender;

However, sometimes it's nice to declare an "optional" property inline with the rest of them, in which case you can use object spread to get the effect you're looking for: 但是,有时很高兴声明与其余部分内联的“可选”属性,在这种情况下,您可以使用对象传播来获得您正在寻找的效果:

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

    ...this.userGender
        ? { gender: this.userGender }
        : {}
}

Try this 试试这个

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

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

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