2017-01-02 112 views
0

quick question:我想創建一個具有多維屬性的對象。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

相關問題