EN VI

Reactjs - How do I assign an interface type to Array<object> returned from an API?

2024-03-14 06:30:06
Reactjs - How do I assign an interface type to Array returned from an API

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

Solution:

You can use assertion:

(results as MyResults[]).map((item) => (
  <>
    <div>{item.name}</div>
    <div>{item.age}</div>
  </>
));
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login