【问题标题】:Typescript: Create an object with multidimensional properties打字稿:创建具有多维属性的对象
【发布时间】:2017-01-02 23:28:52
【问题描述】:

快速问题:我想创建一个具有一些多维属性的对象。

用户类具有性别、生日、身高等属性。

还有体重的多维属性,用户可以在其中添加他的新体重与当前日期。

interface weightData {
    date: Date;
    weight: number;
}

export class UserData {
    sex: string;
    location:string;
    fokus:string;
    birthdate:Date;
    weight:Array<weightData> = [];
    height:number;

    constructor(sex:string, location:string, fokus:string, birthdate:Date, height:number, weight:number) {
        let currentDate: Date = new Date();

        this.sex = sex;
        this.location = location;
        this.fokus = fokus;
        this.birthdate = birthdate;
        this.height = height;
        this.weight.push(
            date: currentDate, //dont work
            weight: 31 // dont work
        );
    }
}

我的 2 个问题:

1:构造函数的正确语法是什么?

2:创建为“权重”添加新值的方法的最佳方法是什么?

非常感谢。

【问题讨论】:

    标签: angular typescript typescript2.0


    【解决方案1】:

    您可以使用公共字段跳过大的初始化开销。并根据您的需要添加一些addWeight 功能。我创建了一个Plunkr

    这里的主要部分:

    interface weightData {
        date: Date;
        weight: number;
    }
    
    export class UserData {
    
        // fields are created public by default
        constructor(public sex:string = 'female', public location:string = 'us', public fokus:string = 'none', public birthdate:Date = new Date(), public height:number = 1, public weight:Array<weightData> = []) {}
    
        // Date optional, use new Date() if not provided
        addWeight(amount: number, date?: Date = new Date()) {
          this.weight.push({date, amount})
        }
    }
    

    【讨论】:

      【解决方案2】:

      这是你要找的吗:

      class UserData {
          sex: string;
          location: string;
          fokus: string;
          birthdate: Date;
          weight: weightData[];
          height: number;
      
          constructor(sex: string, location: string, fokus: string, birthdate: Date, height: number, weight: number | weightData) {
              this.sex = sex;
              this.location = location;
              this.fokus = fokus;
              this.birthdate = birthdate;
              this.height = height;
      
              this.weight = [];
              this.addWeight(weight);
          }
      
          addWeight(weight: number | weightData) {
              if (typeof weight === "number") {
                  this.weight.push({
                      date: new Date(),
                      weight: weight
                  });
              } else {
                  this.weight.push(weight);
              }
          }
      }
      

      (code in playground)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-03
        • 2020-12-17
        • 2020-01-19
        • 2020-08-04
        • 1970-01-01
        • 1970-01-01
        • 2018-12-31
        相关资源
        最近更新 更多