Using Enums and Literal Types
Explore how to define and use enums and literal types in TypeScript to create robust, readable code with improved type safety. Understand enum value assignments and best practices to avoid errors and enhance validation.
We'll cover the following...
TypeScript includes many different ways to specify a type that is limited to a few values. We’ve just looked at literal types, but those are merely a subset of what we can do in TypeScript using an enumerated type, or enum.
Defining enums
The flexibility of TypeScript enums allows us to do many things that at first may seem unuseful.
Simply put, we can define an enum in TypeScript by providing a list of values for it. So, if we wanted to convert our TicketStatus type to an enum, we could do this:
We can then use these statuses as TicketStatus.Unsold, TicketStatus.Held, and so on. Conventionally, the individual elements of ...