javascripttypescriptobjectpropertiesconditional-statements

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. What would the proper syntax for the following be:

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

P.S. I do not wish to have the gender property in my object if there is no value along with it. So how can I only create the property if the condition is satisfied?


Solution

  • 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 }
    }