Mike Poole
Mike Poole

Reputation: 2055

Interface including an array in TypeScript

I have the following JSON:

{
  "items": [
    {
      "id": "123",
      "title": "potatoes",
      "category": "Fruit & Veg"
    },
    {
      "id": "456",
      "title": "custard",
      "category": "Other"
    }
  ]
}

...and the following interface:

export interface ShoppingItems {
  category: string;
  id: number;
  title: string;
}

When I import the JSON it works but I am rightly warned that Property 'items' does not exist on type 'ShoppingItems[]'.

Can I take account of the existence of the items array in the interface or does it need to be accounted for outside of the interface?

Upvotes: 2

Views: 37

Answers (1)

tony
tony

Reputation: 1326

Introduce child interface for a single item

interface ShoppingItem {
  category: string;
  id: number;
  title: string;
}

export interface ShoppingItems {
   items: ShoppingItem[];
}

Upvotes: 3

Related Questions