2016-10-03 33 views
0

財產「GROUPBY」我面臨的,當我想創建一個JSON結構像下面的問題:我在做類似下面錯誤:遺漏的類型錯誤:無法讀取的不確定

enter image description here

所以這:

class Aggregate{ 
    average: Number; 
    count: String; 
    max: Number; 
    min: Number; 
    total: Number; 
    constructor(average,count,max,min,total) { 
     this.average= average; 
     this.count=count; 
     this.max=max; 
     this.min= min; 
     this.total=total; 
    } 
} 

var average = new Aggregate(43.833333333333336, 6, 90, 10, 263); 
var aggregate = new Aggregate(0, undefined, 0, 0, 0); 
var startDate=new Date("Tue Jul 05 2016 05:30:00 GMT+0530 (India Standard Time)"); 
var endDate=new Date("Tue Jul 05 2016 05:30:00 GMT+0530 (India Standard Time)"); 
interface date{ 
    aggregate: Aggregate; 
    endDate: Date; 
    groupBy: String; 
    metricType: String; 
    quarters: Array<DateMetric>; 
    startDate: Date; 
    type: String; 
    quarter?: Number; 
} 
class DateMetric{ 
    aggregate: Aggregate; 
    endDate: Date; 
    groupBy: String; 
    metricType: String; 
    quarters: Array<DateMetric>; 
    startDate: Date; 
    type: String; 
    quarter?: Number; 

    constructor(); 
    constructor(obj: date); 
    constructor(obj?: any) { 
     this.aggregate= aggregate; 
     this.endDate=endDate; 
     this.groupBy=obj.groupBy; 
     this.metricType= obj.metricType; 
     this.quarters = obj.quarters; 
     this.startDate = startDate; 
     this.type = obj.type; 
     this.quarter =obj.quarter; 

    }  
} 
var b = new DateMetric(); 
b.aggregate = aggregate; 
b.quarter=4 
b.startDate = startDate; 


var a = new DateMetric({ aggregate: average, endDate: endDate, groupBy: "datetime", metricType: "distance_metric", quarters: [b], startDate: startDate, type: "person" }) 

但在這裏,我得到一個錯誤說:Cannot read property 'groupBy' of undefined

我不知道爲什麼我收到錯誤爲obj在構造函數中應該包含創建對象時傳遞的對象a

任何幫助,將不勝感激。

+0

您在DateMetric中的構造函數內的'console.log(obj)'中看到了什麼? –

+0

錯誤是由'var b = new DateMetric();'造成的。它不使用1st構造函數,而是使用3rd。 – notgiorgi

+0

@notgiorgi 但爲什麼呢?它不是參數 –

回答

1

定義像這樣的構造函數來擺脫錯誤。

constructor(obj: any | Date = {}) { } 

這種方式如果你創建一個沒有任何數據在構造函數中傳遞的實例,基本上你正在訪問。

{}.groupBy; // ({} aka 'obj' is now defined) 

與您現有的代碼,你也可以先走一步,如果放一個,像這樣:

constructor(obj: any | Date) { 
    if(!!obj) { 
     // do stuff 
    } 
} 

但你上面的例子,第一個解決方案是最好的,我認爲:)

+0

@thanks :)其工作 –

相關問題