简体   繁体   English

类型“从不”上不存在属性“id”。 地图功能

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

So i have started learning Typescript and im a little stuck when it comes to typing the map function below.所以我开始学习 Typescript 并且在输入下面的地图函数时有点卡住了。 When i do nothing i get an error: Property 'id' does not exist on type 'never'.当我什么都不做时,我收到一个错误:“从不”类型上不存在属性“id”。 But if i add 'item:any' to the params of the function it fixes it.但是,如果我将“item:any”添加到函数的参数中,它会修复它。

But everywhere i read they mention that any should be the last resort.但在我读到的任何地方,他们都提到任何应该是最后的手段。 Can someone explain to me how to type this correctly?有人可以向我解释如何正确输入吗?

Bonus: There is also an error with the section 'error.message' which has the same error which i cant seem to resolve either without adding any.奖励:“error.message”部分也有一个错误,它具有相同的错误,我似乎无法在不添加任何内容的情况下解决。

import React, {useState, useEffect} from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);


 useEffect(() => {
 fetch("https://api.publicapis.org/entries")
  .then(res => res.json())
  .then(
    (result) => {
      setIsLoaded(true);
      setItems(result);
    },
   
    (error) => {
      setIsLoaded(true);
      setError(error);
    }
  )
}, [])

if (error) {
  return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
  return <div>Loading...</div>;
} else {
return (
  <ul>
    {items.map((item) => (
      <li key={item.id}>
        {item.name} {item.price}
      </li>
    ))}
  </ul>
);
 }
}

export default App;

You can "easily" fix this by giving TypeScript an hint on what is the type of array of objects you are iterating with map .您可以通过向 TypeScript 提供有关您正在使用map迭代的对象数组类型的提示来“轻松”解决此问题。

This can be done by using the generic parameter that useState receives, here is a sample:这可以通过使用useState接收的泛型参数来useState ,这里是一个示例:

interface Item {
  id: string;
  name: string;
  price: number;
}

// Then you need to pass in the type of what you will have in the useState
const [items, setItems] = useState<Array<Item>>([]);

The problem you are facing is due to TypeScript having no clue on what is the type of the objects that items may or may not contain.您面临的问题是由于 TypeScript 不知道items可能包含或不包含的对象的type Which will make items fallback to the type of never[] , which is just a way of TypeScript warning you that you made something wrong and that you can't use it that way.这将使items回退到never[]类型,这只是 TypeScript 警告您做错了什么并且不能那样使用它的一种方式。

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

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