Skip to content

Typing Pizza App part 5

von Schappler edited this page Oct 27, 2024 · 2 revisions

Adding literal types and unions definitions to Pizza App

A way in which we could add more type safety to our pizza application is by specifying on our code that an order status can not be "any string" (as we have it right now), but also specifying the literal values that the status can be assigned to.


Setting the literal types for order status

The snippet below shows how it's possible to achive the aditional layer of type sefety to the order status:

type Order = {
  id: number;
  pizza: Pizza;
  status: 'ordered' | 'completed';
};

Notice tough, that this would now cause an type error for when a new order is being created, and that can be fixed by setting the correct type to newOrder:

const newOrder: Order = { id: orderId++, pizza, status: 'ordered' };

Clone this wiki locally