![](/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.