I have a REST API that gives data in the following format:-
{"id": 1, "name": "New event", "date": "2020-11-14T18:02:00"}
And an interface in my frontend React app like this:-
export interface MyEvent {
id: number;
name: string;
date: Date;
}
I use axios to fetch response from the API.
const response = await axios.get<MyEvent>("/event/1");
const data = response.data;
However, data.date remains a string due to typescript limitations.
This can cause problems later in the code, where I expect all such date fields to be an actual Date object.
I could probably do something like: data.date = new Date(data.date);. But that won't be feasible approach for a lot of reasons.
Is there a better way of handling dates in typescript? How do you handle dates coming from API in response in general?
Angular Http Interceptor. It recursively walks the object structure looking for string values that match the ISO-8601 date format, and replace matches with the date object. This would need to be adapted to Axios, but I hope this helps. Cheers.