I’m new to both typescript and react. I have a React app that returns values from a REST call to a database API. I’m using a 3rd party library that calls the API and returns the results. As a simplified example the results are defined by an interface in library (that I have no control over) like this:
interface Response {
results: Array<object>
}
I assume the library does this because the results returned are based on the structure of the table that is user defined which the library authors couldn’t know. My question is assuming I know the structure of the table how would I assign (typecast?) the results returned to an interface I defined?
For example, if I know the results of the object inside the Array could be defined as:
interface MyResults {
name: string
age: number
}
ideally I’d like to so something like this in JSX:
return(
{results.map((item: MyResults) => <div>{item.name}</div><div>{item.age}</div>
)
When I try this though I get an error like this:
Argument of type '(item: MyResults) => React.JSX.Element' is not assignable to parameter of type '(value: object, index: number, array: object[]) => Element
2
Answers
the problem is in the jsx component
your problem could solved with this code
in your case you can transform the Response in your custom object response as long as the properties match
You can use assertion: