簡體   English   中英

如何在 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... 
        ]
    }
}

這是我目前擁有的解決方案。 codeproductNameprices工作正常,但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中的使用比較棘手,一般不推薦。 你在這里有兩個問題:

  1. object是一個模棱兩可的類型,所以你不能使用prices.nationalPrices因為nationalPricesobject類型上不存在
  2. 修復此問題后,您還將遇到一個錯誤,即 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM