I have the following type of object on my client side (typescript):
interface Example {
id: number;
name: string;
createdOnDate: Date;
}
I'm fetching data from the server that matches the type (same property names):
async function fetchExamples(): Promise<Example[]> {
const response = await fetch("/example/index");
if (!response.ok) {
throw Error("...");
}
return (await response.json()) as Example[];
}
The problem is that, the createdOnDate
is returned from the server as a string in an ISO format (such as 2019-01-01T14:30:39.0000000Z
for example). As you can guess, the createdOnDate
on the client doesn't get parsed to a Date
, but it remains a string.
Is there a way to cast it automatically without iterating through all of the response data. I have the following, which works as expected:
function parseDateFromServer(date: string): Date {
if (date) {
return typeof date === "string" ? new Date(date) : date;
}
return null;
}
async function fetchExamples(): Promise<Example[]> {
const response = await fetch("/example/index");
if (!response.ok) {
throw Error("...");
}
const data = await response.json();
const parsedData: Example[] = data.map(
(x) =>
({
...x,
createdOnDate: parseDateFromServer(x.createdOnDate)
} as Example)
);
return parsedData;
}
I was wondering if I can do it in a more "elegant" way (also I have this code throughout my codebase, I'd rather not go and change it everywhere and my real types are quite more complex than this example one).