【问题标题】:Typescript - Conditional property of object打字稿 - 对象的条件属性
【发布时间】:2018-12-31 08:09:02
【问题描述】:

我希望拥有以下对象的条件属性:

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

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

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

附:如果没有任何价值,我希望在我的对象中有 gender 属性。那么如何才能在条件满足的情况下才创建属性呢?

【问题讨论】:

  • 您是否有理由不只是有条件地分配 userGender? let myObject = { /*object without gender */ }; if(this.userGender) myObject.gender = this.userGender;
  • 它在 Dart 中可用 - 我希望它可以被引入到打字稿中

标签: javascript typescript object properties conditional


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    也可以这样;

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

    【讨论】:

      【解决方案3】:

      试试这个

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

      【讨论】:

      • 最后一行的 :gender 做了什么?我看不到任何文档中的描述。
      猜你喜欢
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 2017-01-04
      • 2019-07-28
      • 2019-10-03
      • 2020-12-17
      • 1970-01-01
      • 2021-11-06
      相关资源
      最近更新 更多