Issue
I am building a react frontend client using typescript. I would like to make a request to an api endpoint that will return a list of events. When I get the response from this event I want to map it to an internal type, that will also have extra properties not returned from the API, specifically, I want to associate an icon to an internal type for when it is rendered. The icon is not part of the API and I do not want it to be so it does not couple the front end to the API. API response:
[
{
"identifier": "1",
"name": "Gig"
},
{
"identifier": "2",
"name": "Concert"
},
{
"identifier": "3",
"name": "Some event type here"
}
{
"identifier": "4",
"name": "other"
}
]
So I can request this fine, but I want to map that response back to an internal type of the following definition:
type Event = {
identifier: string;
name: string;
icon: string;
}
Somewhere I want to map the returned labels from the API to an internal list that holds the corresponding icons. I am not sure of the best way to do this, for that mapping to take place I will need an internal list of potential types that will be returned and the icons, or how to do that mapping?
Solution
I believe you can use interfaces that can inherit from another interface in this case. You can have 2 interfaces that can be used as your type.
interface Event{
identifier: string;
name: string;
}
interface EventICON extends Event {
icon: string;
}
The Event
interface can be used to map your API response and EventICON
can be used after you inject your icon list inside the response you get.
Answered By - Sanish Joseph
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.