Member-only story
TypeScript Enums and Generics: Simplified
How to use Enums and Generics
Two essential features that TypeScript provides are enums and generics. Enums allow you to define a set of named constants, while generics provide a way to create flexible and reusable code components.
Understanding Enums
Enums, short for enumerations, allow you to define a set of named numeric constants. They make your code more expressive and self-documenting, especially when dealing with a fixed set of values.
Let’s say you’re working on a project that involves days of the week. Instead of using plain strings or numbers, you can use an enum to define these days:
enum DaysOfWeek {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
// Using the enum values
const today: DaysOfWeek = DaysOfWeek.Wednesday;
console.log(`Today is ${DaysOfWeek[today]}`);
In this example, we’ve defined an enum
called DaysOfWeek
with the days of the week as its members. Enums start indexing from 0 by default, so DaysOfWeek.Wednesday
corresponds to the value 3
. You can access the name of an enum member using DaysOfWeek[today]
.
Enums are a great way to ensure that you’re using valid values, and they improve code readability.