使用打字稿時出現此錯誤。
Type 'string' is not assignable to type 'never'.
它在 javascript 上運行良好。
const [gifList, setGifList] = useState([])
const sendGif = async () => {
if (inputValue.length > 0) {
console.log('Gif link:', inputValue)
setGifList([...gifList, inputValue])
setInputValue('')
} else {
console.log('Empty input. Try again')
}
}
您能否告訴我如何在 Typescript 中正確宣告型別。
uj5u.com熱心網友回復:
const [gifList, setGifList] = useState([])
由于您尚未在此處定義型別,因此 typescript 會做出最好的猜測。它看到您將狀態設定為一個陣列,但它不知道該陣列中應該包含什么,因此它可以做的最好的是將狀態視為never[].
useState是泛型的,因此您可以使用它來指定狀態的型別:
const [gifList, setGifList] = useState<string[]>([])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/445946.html
上一篇:是否可以在打字稿中跳過深度級別?
