我在打字稿中遇到了這個錯誤
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
當我嘗試動態訪問物件屬性時:
import React, { useState } from "react";
const cities = {
ny: {
label: "New York"
},
ld: {
label: "London"
}
};
export default function App() {
const [city, setCity] = useState<string>("ny");
console.log(cities[city].label); //what's wrong here
return (
<div className="App">
hi
</div>
);
}
任何線索如何擺脫這樣的錯誤?
uj5u.com熱心網友回復:
您說城市在宣告時只有兩個鍵:“ny”和“ld”,但是您允許任何城市成為您的城市元素的鍵。
改變:
useState<string>
到
useState<"ny" | "ld">("ny")
應該可以解決您的問題。
如果你想允許更多的城市,你也可以采用這種方法:
type City = {
[key: string]: {
label: string;
};
};
const cities: City = {
ny: {
label: "New York",
},
ld: {
label: "London",
},
};
并保持你的 useState。
最后,您可以使用以下命令根據您的城市 const 動態生成可能的密鑰:
const [city, setCity] = useState<keyof typeof cities>("ny");
uj5u.com熱心網友回復:
如果string沒有索引型別,您就不能使用型別來訪問物件上的屬性。但是如果你使用useState<keyof typeof cities>("ny");它會發現它不僅僅是一個字串,而是一個物件中的特定字串(在這種情況下是“ny”和“ld”)。
enum如果需要,您還可以使用和索引型別:)
uj5u.com熱心網友回復:
cities是無型別的,而且cities.ny它實際上是“隱式具有'任何'型別”。要消除此錯誤,您應該為變數提供型別,例如,您可以執行以下操作:
interface City {
label: string
}
const cities: {[name: string]: City} = {
ny: {
label: "New York"
},
ld: {
label: "London"
}
};
并且編譯器會知道label.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/364354.html
