0

I am trying to create a model for my categories object below:

{
    "categories": [
        {
            "sandwiches": [
                {
                    "name": "breadedChickenFlatbread",
                    "description": "A good sandwich",
                    "img": "./sandwich.jpg",
                    "price": "$8.99"
                }
            ]
        },
        {
            "pizzas": [
                {
                    "name": "PizzaPie",
                    "price": "5milliondollars",
                    "img": "",
                    "description": ""
                }
            ]
        }
    ]
}

I'm not sure how to create the model portion for "categories" since the data items can change. For example, instead of "sandwiches" and "pizzas", the api could return "burgers" and "sides".

Here is what I have:

export class Menu {
    categories: Array<Category>;
}

class Category {
    // ?
}

// Details will always be the same
class Details {
    name: string;
    description: string;
    img: string;
    price: string;
}

How can I map the category names in my object, to my model? Or should the response object be changed

1 Answer 1

1

so a category could be typed like:

interface Category {
  [key:string]: Details[];
}

this is an index signature which basically means the type category has some number of string keys that will have a Details array type value.

You can type the key with a literal to be stricter:

type CategoryKey = 'pizzas'|'sandwiches'|'burgers'|'fries';

interface Category {
  [key:CategoryKey]: Details[];
}

now the category interface can only have those specific keys.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.