【发布时间】:2021-12-30 09:18:38
【问题描述】:
我有一个运行良好的 React/GraphQL 小型应用程序,我正在尝试向其中添加 TypeScript,因为我是 TypeScript 的新手并正在尝试学习它。我有一个 GraphQL API 端点,它返回产品和这些产品的信息。使用 React,我将产品存储在一个状态中,然后使用 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>
</>
)
}
【问题讨论】:
-
旁注,你会喜欢的,在使用 GraphQl 时省去了打字稿类型的所有麻烦...npmjs.com/package/@graphql-codegen/cli
-
在模板中,您引用的
product.prices.nationalPrices根据您的上述类型不存在。你输入了Product.prices,只是一个普通的object。遵循@James 的回答将解决此问题。
标签: javascript reactjs typescript graphql