繁体   English   中英

如何修复 TypeScript 错误?

[英]How to fix TypeScript errors?

几天前开始学习 typescript,到目前为止,这对我来说都是地狱)我希望这是值得的。 当我阅读有关 TS 的文章时看起来很容易,但是很难正确地写出任何东西 - 现在每次更正都会产生越来越多的 TS 错误。 对不起,对于那个介绍:)

我有 function(下面的代码),几乎没有错误,也不知道如何解决。

  1. 错误:TS2532:Object 可能是“未定义”。
  2. 错误:TS2339:类型“项目”上不存在属性“地图”。
  3. 错误:TS7006:参数“item”隐式具有“any”类型。

尝试阅读类似的问题,尝试不同的修复方法,但我不断收到错误。 任何人都可以告诉我如何解决此类错误或提供建议吗?

interface Items {
  items: any[]
  map: [] 
  //tried to add map like this but got another error - 
  //TS2349: This expression is not callable. Type '[]' has no call signatures.
}

const ItemsList: React.FC<Items> = () => {
  const [items, setItems] = useState<Items>();
  useEffect(() => {
    const response = Http.get<Items>(url).then(res => setItems(res))
  }, [])

  return (
      <ul>
        {items.map((item) => { // all errors here
          return (
            <ItemPreview key={item.id} item={item}/>
          );
        })}
      </ul>
  )
}

export default ItemsList

你可以通过我添加的评论go:

interface Item {
    id: string;
    // ... add other props here
}

type Items = Item[]

// looks like you're not sending any props to this component so `React.FC` is sufficient
const ItemsList: React.FC = () => {

    // By giving an empty array to `useState`, `items` will always be defined
    // an alternative would be to check if `items` is populated and only render when it is
    const [items, setItems] = useState<Items>([]);

    useEffect(() => {
        // you can give a type to `res` if the response you get here is an array of `Item`s
        // if not, adjust the type accordingly
        Http.get<Items>(url).then((res: Items) => setItems(res))
    }, [])

    return (
        <ul>
            {items.map((item) => { // you no longer need to give any types here
                return (
                    <ItemPreview key={item.id} item={item}/>
                );
            })}
        </ul>
    )
}

暂无
暂无

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

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