Shikha thakur Shikha thakur - 2 months ago 12
TypeScript Question

Error:Uncaught TypeError: Cannot read property 'groupBy' of undefined

I am facing an issue when i am trying to create a JSON structure like below:

enter image description here

so for this i am doing like below:

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


but here i am getting an error saying:
Cannot read property 'groupBy' of undefined


I have no idea why i am getting the error as
obj
in constructor should contain the object passed when creating an object
a


Any help would be appreciated.

Answer

Define your constructor like this to get rid of the error.

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

this way if you create an instance without any data passed in the constructor, basically you are accessing.

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

With your existing code you can also just go ahead and put an if, like so:

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

But for your example above, the first solution is best in my opinion :)