Dates in the Typescript interface are actually strings when validated

Unfortunately, the general code for reproducing this will be extensive, so I hope my problem is obvious because I can easily provide it. If necessary, I will send a more complete solution.

First, I define the interface:

export interface ITest {
    myDate: Date;
}

Then I create an array of them for testing:

export const TEST: ITest[]=[{myDate: new Date(1995, 8, 1)}]

I expose them using a service in Angular2 that gets into InMemoryDbService from angular2-in-memory-web-api. The code where I call this and get the array looks like this:

get(): Promise<ITest[]>{
    return this.http.get(this.testUrl)
        .toPromise()
        .then(response => response.json().data as ITest[])
        .catch(this.handleError);
}

... and then I put it into my component with:

    this.testService.get().then(tests => {
        this.tests = tests;
        console.log("Date Type:"+typeof(this.tests[0].myDate));
    });

This all works fine, but the problem is the expression console.logshown here:

Date Type:string

, , , 1995-09-01T07:00:00.000Z, - Date, string! VS Code toDateString, , () toDateString is not a function.

, response => response.json().data as ITest[], Date? , . , , ?

+4
1

, TypeScript, .

, , , - json-, myDate .

type-assertion javascript - .

, , , JSON Date , , , date.toString().

- JSON :

var response = JSON.parse(JSON.stringify({ myDate: new Date() }));

class Test  {
    constructor(json: { myDate: string }) {

        this.myDate = new Date(json.myDate);
    }

    myDate: Date;
}

let test = new Test(response);
console.log("Type: " + typeof (test.myDate));
console.log("Value: " + test.myDate);
+4

Source: https://habr.com/ru/post/1657105/


All Articles