For all those who came here and did indeed use Date typed Variables, here is the solution I found. It does also apply to TypeScript.
I was facing this error because I tried to compare two dates using the following Method
var res = dat1.getTime() > dat2.getTime(); // or any other comparison operator
However Im sure I used a Date object, because Im using angularjs with typescript, and I got the data from a typed API call.
Im not sure why the error is raised, but I assume that because my Object was created by JSON deserialisation, possibly the getTime()
method was simply not added to the prototype.
Solution
In this case, recreating a date-Object based on your dates will fix the issue.
var res = new Date(dat1).getTime() > new Date(dat2).getTime()
Edit:
I was right about this. Types will be cast to the according type but they wont be instanciated. Hence there will be a string cast to a date, which will obviously result in a runtime exception.
The trick is, if you use interfaces with non primitive only data such as dates or functions, you will need to perform a mapping after your http request.
class Details {
description: string;
date: Date;
score: number;
approved: boolean;
constructor(data: any) {
Object.assign(this, data);
}
}
and to perform the mapping:
public getDetails(id: number): Promise<Details> {
return this.http
.get<Details>(`${this.baseUrl}/api/details/${id}`)
.map(response => new Details(response.json()))
.toPromise();
}
for arrays use:
public getDetails(): Promise<Details[]> {
return this.http
.get<Details>(`${this.baseUrl}/api/details`)
.map(response => {
const array = JSON.parse(response.json()) as any[];
const details = array.map(data => new Details(data));
return details;
})
.toPromise();
}
For credits and further information about this topic follow the link.