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?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…