Home > database >  How to type a nested object?
How to type a nested object?

Time:08-21

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.

And then reference the type as such:

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

CodePudding user response:

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.

  • Related