Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 786
Smitherson Avatar asked Jul 23 '18 19:07

Smitherson


2 Answers

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 }
        : {}
}
like image 85
CRice Avatar answered Sep 22 '22 08:09

CRice


it can be done like this too, more clean and readable.

const myObj = {
    name: this.username,
    DOB: new Date(this.inputDate),
    ...(this.userGender && { gender : this.userGender })
}
like image 45
Amir Avatar answered Sep 19 '22 08:09

Amir