I have a typescript interface that has a variable (start) as a Date | null typing. This data is fetched from dotnet API which returns a DateTime object. The start variable is run through a Date-fns function which throws the error a RangeError because Date-fns has changed the function to only accept dates.
Invalid time value
react_devtools_backend.js:4026 Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use
parseISOto parse strings
The problem I'm having is that I thought that start was already a date object, but when I print to console, it's actually a string. I could fix this problem by simply parsing it, however, I'd like to know why its not the correct typing.
console.log("I am a" + typeof(raceEvent.start!))
console.log(raceEvent.start)
I am astring
2022-04-28T08:30:00
Typescript interface:
export interface RaceEvent {
id: string;
sponsor: string;
logo: string;
prefix: string;
name: string;
postfix: string;
start: Date | null;
end: Date | null;
}
C# Class:
public class RaceEvent
{
public Guid Id { get; set; }
public string? Sponsor { get; set; }
public string? Prefix { get; set; }
public string Name { get; set; }
public string? Postfix { get; set; }
public string? Logo { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
}
Load Event function
loadEvent = async (eventId: string) => {
this.loadingInitial = true;
try {
let raceEvent = await agent.Events.details(eventId);
runInAction(() => {
this.selectedEvent = raceEvent;
this.loadingInitial = false;
});
} catch (error) {
console.log(error);
runInAction(() => {
this.loadingInitial = false;
});
}
};
agent.ts
const Events = {
details: (id: string) => requests.get<RaceEvent>(`/raceEvents/${id}`),
};
const responseBody = <T>(response: AxiosResponse<T>) => response.data;
const requests = {
get: <T>(url: string) => axios.get<T>(url).then(responseBody),
post: <T>(url: string, body: {}) => axios.post<T>(url, body).then(responseBody),
put: <T>(url: string, body: {}) => axios.put<T>(url, body).then(responseBody),
del: <T>(url: string) => axios.delete<T>(url).then(responseBody),
};
RaceEventinterface, but where do you parse the result of the API call to that type?JSON.parsefunction that attempts to convert it to a date (under certain conditions).