Skip to content

Typing Pizza App part 6

von Schappler edited this page Oct 27, 2024 · 1 revision

Adding ids to Pizzas on Pizza App

Even though TypeScript offers a good type inference on primitive or complext types, as part of good practices it's always good to manually declare those types.

If we check our menu variable declaration for example, type script is infering that menu is an array of objects, but not which is the type of those objects.

It's important to note that, even though the objects added to menu conform to the type Pizza, they are not really Pizza types - and this can be really seen if we change the Pizza type by adding the id property to it.


Adding id to the Pizza type:

What happens when we add the id property to our code, like in the snippet below?

type Pizza = {
  id: number;
  name: string;
  price: number;
};
  • menu does not have any problems with type checking, because it does not have a type defined as an array of pizzas
  • Other parts of the code where the pizza type is being used will start complaning about the missing property

To fix the first problem, all we need to do is to set the correct type for menu as Pizza[], like so:

const menu: Pizza[] = [
  {
    name: 'Margherita',
    price: 8,
  },
  {
    name: 'Pepperoni',
    price: 10,
  },
  {
    name: 'Hawaiian',
    price: 10,
  },
  {
    name: 'Veggie',
    price: 9,
  },
];

This will now lead us to the second part, where no id property is given by any Pizza type variables in our application.

For now, to fix temporarily this issue, we are going to set manually the id property to every pizza object which is showing the warning where the id porperty is missing.

Clone this wiki locally