Home > Back-end >  Property 'id' does not exist on type 'never'. typescript
Property 'id' does not exist on type 'never'. typescript

Time:07-21

i've trying to show image from JSON api and then show it to page, i was do it succesfully but for some reason when i go to page i've get this errors

Property 'id' does not exist on type 'never'.
Property 'url' does not exist on type 'never'.
Property 'title' does not exist on type 'never'.

here is the code

 const App = () => {
 const [images, setImages] = useState([]);
 useEffect(() => {
 fetch('https://api.thecatapi.com/v1/images/search?breed_id=abys')
  .then(res => res.json())
  .then(json => setImages(json))
  .catch(err => console.log(err));
}
, []);
return (
<Fragment>
  <div className="App">
    <h1>Image Gallery</h1>
    <div className="image-container">
      {images.map(image => (
        <Image key={image.id} image={image.url} alt={image.title} />
      ))}
    </div>
  </div>
</Fragment>
);
}

CodePudding user response:

You havent declared a type for image in your useState

const [images, setImages] = useState([]);

so it is considered as type never.

What you should do is add an interface eg IImage and then declare it in your useState

export default interface IImage {
  id: number
  url: string
  title: string
}

const [images, setImages] = useState<IImage[]>([]);
  • Related