Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to type a nested object?

I want to type an object to include it in a React state. This is a shopping cart object with a couple of product IDs and their props.

Object:

{
  "1047151242": {
      "name": "Item 1 name",
      "price": 22.99,
      "quantity": 2,
      "subtotal": 45.98
  },
  "3327300382": {
      "name": "Item 2 name",
      "price": 90.49,
      "quantity": 2,
      "subtotal": 180.98
  }
}

etc. where the product ID can be any string of the same format.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And then reference the type as such:

const [cart, setCart] = useState<CartInterface>(CartState);

>Solution :

If I understand correctly, you just need a type

type CartInterface = {
    [s: string]: {
        name: string;
        price: number;
        quantity: number;
        subtotal: number;
    }
}

Now when you use it like you mentioned, cart will be of type CartInterface.
If this answers your question, I suggest some deeper reading of the typescript documentation.
You can check this playground link to see it in action.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading