[英]typescript access object dynamically
我在 typescript 中收到此錯誤
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
當我嘗試動態訪問 object 屬性時:
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>
);
}
任何線索如何擺脫這種錯誤?
您說城市在聲明時只有兩個鍵:“ny”和“ld”,但是您允許任何城市成為您的城市元素的鍵。
改變:
useState<string>
至
useState<"ny" | "ld">("ny")
應該可以解決您的問題。
如果你想允許更多的城市,你也可以用這種方法 go :
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");
您不能使用string
類型來訪問沒有索引類型的 object 上的屬性。 但是如果你使用useState<keyof typeof cities>("ny");
這將表明它不僅僅是一個字符串,而是對象中的特定字符串(在這種情況下為“ny”和“ld”)。
如果需要,您還可以使用enum
和索引類型:)
cities
是無類型的, cities.ny
也是,它的字面意思是“隱式具有'任何'類型”。 為了擺脫這個錯誤,你應該為你的變量提供類型,例如你可以這樣做:
interface City {
label: string
}
const cities: {[name: string]: City} = {
ny: {
label: "New York"
},
ld: {
label: "London"
}
};
編譯器會知道label
的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.