打字稿:创建具有多维属性的对象

时间:2017-01-02 14:56:18

标签: angular typescript typescript2.0

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

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

还有权重的多维属性,用户可以在当前日期添加新的权重。

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:创建一个为“重量”添加新值的方法的最佳方法是什么?

非常感谢。

2 个答案:

答案 0 :(得分:1)

你可以跳过公共字段的大init开销。并根据您的需要添加一些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})
    }
}

答案 1 :(得分:0)

这就是你要找的东西:

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