Enum vs Union Literal Type Trade-offs in TypeScript
📖 Scenario: Imagine you are building a simple app that tracks the status of orders in a store. You want to represent the order status using TypeScript types. You will explore two ways to do this: using enum and using union literal types. This will help you understand the differences and trade-offs between these two approaches.
🎯 Goal: You will create two ways to represent order statuses: one with an enum and one with a union literal type. Then you will write a function that accepts only valid statuses and prints a message. Finally, you will see how the output looks for both approaches.
📋 What You'll Learn
Create an
enum called OrderStatusEnum with values Pending, Shipped, and DeliveredCreate a union literal type called
OrderStatusUnion with the string literals 'Pending', 'Shipped', and 'Delivered'Write a function
printStatusEnum that takes a parameter status of type OrderStatusEnum and prints a messageWrite a function
printStatusUnion that takes a parameter status of type OrderStatusUnion and prints a messageCall both functions with the
Shipped status and print the results💡 Why This Matters
🌍 Real World
Enums and union literal types are common ways to represent fixed sets of values in TypeScript, such as status codes, user roles, or options in forms.
💼 Career
Understanding these types helps you write safer and clearer code in TypeScript, which is widely used in web development and many software projects.
Progress0 / 4 steps