2017-01-02 9 views
0

簡単な質問:いくつかの多次元プロパティを持つオブジェクトを作成したいと思います。Typescript:多次元プロパティを持つオブジェクトを作成する

ユーザークラスには、性別、生年月日、身長などのプロパティがあります。

また、ユーザが現在の日付で新しい重みを追加できる、多次元の重みのプロパティ。ここ

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:「ウェイト」に新しい値を追加する方法を作成するにはどうすればよいですか?

ありがとうございます。

答えて

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}) 
    } 
} 
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

関連する問題