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)