简体   繁体   English

“从不”类型上不存在属性“id”。 打字稿

[英]Property 'id' does not exist on type 'never'. typescript

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我试图从 JSON api 显示图像,然后将其显示到页面,我成功地做到了,但是由于某种原因,当我转到页面时,我得到了这个错误

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>
);
}

You havent declared a type for image in your useState您尚未在useState中声明image类型

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

so it is considered as type never .所以它被认为是类型never

What you should do is add an interface eg IImage and then declare it in your useState你应该做的是添加一个接口,例如IImage然后在你的useState中声明它

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM