所以我開始學習 Typescript 并且在輸入下面的地圖函式時有點卡住了。當我什么都不做時,我收到一個錯誤:“從不”型別上不存在屬性“id”。但是,如果我將“item: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;
uj5u.com熱心網友回復:
您可以通過向 TypeScript 提供有關您正在迭代的物件陣列的型別的提示來“輕松”解決此問題map。
這可以通過使用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>>([]);
您面臨的問題是由于 TypeScript 不知道可能包含或不包含type的物件是什么items。這將items回退到 的型別never[],這只是 TypeScript 警告您做錯了什么并且不能那樣使用它的一種方式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/349975.html
上一篇:展平嵌套物件打字稿
