2017-01-02 114 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

相关问题