0

I have quite a common case in angular service request data from backend, and the

HttpClient http.get<T>(..) 

is used, where T is a TypeScript interface

Let's say the the response looks as the following:

    {
        "orderId": "61330543",
        "timestamp": "2023-03-01T22:11:16", 
        ..  
    }

thus the interface will look as:

    interface IOrder{
        orderId: string,
        timestamp: Date,  // note strict Date type
        ...
    }

   const response$ : Observable<IOrder>  = this.http.get<IOrder>(...);

in component template :

    <ng-container *ngIf="(response$ | async) as response">
     ...
    {{response.timestamp}}  
    ...

the value will be displayed but the value is not of a Date type as described by IOrder interface, it is a string type!

Why the response was smoothly casted to IOrder interface, although some props do not match their types?

response$.subscribe(response =>

          const timestamp = response.timestamp; 
          
          const type = typeof(timestamp);
          console.log('type: ', type, timestamp);
    }

the output is:

type: string 2023-03-03T01:28:30

Seems found an answer in this question

The problem is that Typescript typings disappear at runtime. Because of this, there is no way for Javascript to know which type you expect from a JSON payload that arrives at runtime. If somebody has an automated way of doing it, I'm interested in knowing it. Otherwise, you'll have to do it manually by wrapping the fields with new Date(payload.myField)

Artem Vertiy
  • 1,002
  • 15
  • 31
  • Does this question depend on angular? If so you might want to tag it as such. If not you might want to remove your example code's dependency on it so it's a [mre] without reference to external code. – jcalz Mar 04 '23 at 19:28
  • angular is mentioned due to HttpClient from @angular/common/http is used and json deserialization and type cast is done by it, basically there are 2 issues: date string is not deserializaed into Date type but that's a side issue, the main issue is mention in the question - interface does not guarantee that object's property will be the type declared in interface i.e. type check is missing that's misleading due to TypeScript seems is needed to protect from type mismatch issues that js allows. – Artem Vertiy Mar 04 '23 at 20:54

1 Answers1

1

The HttpClient will not do the conversion from string to Date for you.

You will have to it yourself.

Matthieu Riegler
  • 31,918
  • 20
  • 95
  • 134