Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

reactjs - Casting dates properly from an API response in typescript

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One option that I have personally used is to create a utility function that parses the input from any to MyEvent. You could do something like this:

function createMyEvent(data: any): MyEvent {
    return {
        id: data.id,
        name: data.name,
        date: new Date(data.date)
    };
}

Then use it like this:

// Same as before, but without a type specified.
const response = await axios.get("/event/1");
// Type is still "MyEvent", but this time its valid.
const data = createMyEvent(response.data);

To make this fully type-safe, the function should also validate the input object to verify that it has the correct field in the correct formats. This is especially important if you are concerned that the schema of MyEvent could be changed by the API without a matching change to the client.

You can also, if needed, use Record<string, unknown> instead of any if you are working in a codebase with noExplicitAny enabled. Both methods will require additional type assertions in createMyEvent, but the basic idea remains the same.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...