skip to Main Content

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


  1. the problem is in the jsx component

    return(
    
    {results.map((item: MyResults) => <div>{item.name}</div><div>{item.age}</div>
    
    )
    

    your problem could solved with this code

            return(
            <div>
    
            {
    results.map((item: MyResults) => 
        <div key={item.name}>
        <p>{item.name}</p><p>{item.age}</p>
        </div>
    )
        }
            </div>
            )
    

    in your case you can transform the Response in your custom object response as long as the properties match

    Login or Signup to reply.
  2. You can use assertion:

    (results as MyResults[]).map((item) => (
      <>
        <div>{item.name}</div>
        <div>{item.age}</div>
      </>
    ));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search