Typescript - Conditional property of object

12,343

Solution 1

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 }
        : {}
}

Solution 2

it can be done like this too ;

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

Share:
12,343
Smitherson
Author by

Smitherson

Updated on June 05, 2022

Comments

  • Smitherson
    Smitherson almost 2 years

    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?

  • Anthony Wieser
    Anthony Wieser over 4 years
    What does :gender do on the last line? I can't see where that's described in any documentation.
  • Allen Luce
    Allen Luce about 2 years
    I don't believe the first form works in TypeScript: Property 'gender' does not exist on type '{ name: string; DOB: Date; }'.
  • cprcrack
    cprcrack about 2 years
    You can also use undefined instead of {} as { ...undefined } has the same effect as { ...{} } (empty object)