首页 > 解决方案 > 打字稿 - 对象的条件属性

问题描述

我有以下对象,我希望有一个条件属性:

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

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

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

PS如果没有价值,我希望在我的对象中拥有该属性。gender那么,如果条件满足,我怎样才能创建属性呢?

标签: javascripttypescriptobjectpropertiesconditional

解决方案


理想情况下,您只需在声明对象后添加适当的属性作为第二个操作。所以像:

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

推荐阅读