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

Typescript: Create an object with multidimensional properties

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

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

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

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:创建向 "weight" 添加新值的方法的最佳方法是什么?

非常感谢。

这是您要找的吗:

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)

您可以使用 public 字段跳过较大的初始化开销。并根据您的需要添加一些 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})
    }
}