![](/img/trans.png)
[英]how to fix 'Property 'dials' does not exist on type 'Object' in typeScript
[英]How to use nested objects in TypeScript? Property does not exist on type 'object'
我有一個 React/GraphQL 小型應用程序運行良好,我正在嘗試將 TypeScript 添加到其中,因為我是 TypeScript 的新手並正在嘗試學習它。 我有一個 GraphQL API 端點,它返回產品和有關這些產品的信息。 使用 React,我將產品存儲在 state 中,然后使用 JSX 渲染每個產品。
我創建了一個Product
類型,其中包含我希望 API 返回的信息,但它也返回嵌套對象,並且我嘗試的所有操作都會觸發 TypeScript 錯誤。 這是 API 返回的簡化示例:
{
"data": {
"products": [
{
"productName": "Soda",
"code": "sod",
"prices": {
"nationalPrices": {
"localPrices": [
{
"pricePerUnit": "1.99"
}
],
"regionalPrices": [
{
"pricePerUnit": "2.49"
}
]
},
"vendorPrices": {
"localPrices": [
{
"pricePerUnit": "1.49"
}
]
}
}
},
// more products...
]
}
}
這是我目前擁有的解決方案。 code
, productName
和prices
工作正常,但nationalPrices
正在觸發 TypeScript 錯誤property nationalPrices does not exist on type 'object'
。 我能做些什么來解決這個錯誤?
type nationalPricesObject = {
localPrices: object[];
}
type Product = {
code: string;
productName: string;
prices: object;
nationalPrices: nationalPricesObject;
}
function ProductList() {
const [products, setProducts] = useState < Product[] > ([]);
const { loading, data, error } = useQuery(LOAD_PRODUCTS);
useEffect(() => {
if (data) {
setProducts(data.products);
}
}, [data]);
return (
<>
<div>
{products.map(p =>
(
<div>
<ProductCard
productName={p.displayName}
code={p.code}
// simplified code below for sake of clearity
pricePerUnit={p.prices.nationalPrices.localPrices[0]['pricePerUnit']}
/>
</div>
))}
</div>
</>
)
}
產品不包含nationalPrices
屬性。 Product.prices 確實如此。 我們可以設置一個包含 Product.prices 中預期內容的價格類型,並使用它來定義產品 object 的價格屬性。
type Prices = {
nationalPrices: nationalPricesObject;
vendorPrices: someOtherPricesObject;
}
type Product = {
code: string;
productName: string;
prices: Prices;
}
object 在object
中的使用比較棘手,一般不推薦。 你在這里有兩個問題:
object
是一個模棱兩可的類型,所以你不能使用prices.nationalPrices
因為nationalPrices
在object
類型上不存在object
localPrices[0]
沒有pricePerUnit
要解決這些問題,請讓您的類型更具體:
type nationalPricesObject = {
localPrices: { pricePerUnit: number; }[]; // assuming this is number?
}
type Product = {
code: string;
productName: string;
prices: nationalPricesObject;
}
最后,按照慣例,typescript 中的類型應該是PascalCase
,並且應該首選接口。 因此,我會將您的代碼更改為:
interface Price {
pricePerUnit: number;
}
interface NationalPrices {
localPrices: Price[];
}
interface Product {
code: string;
productName: string;
prices: NationalPrices;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.