chapter four

4 Enums and Generics

 

This chapter covers:

  • The benefits of using enums
  • The syntax for numeric and string enums
  • What generic types are for
  • How to write classes, interfaces, and functions that support generics

4.1  Enums

Enumerations (a.k.a. enums) allow you to create limited sets of named constants that have something in common. For example, a week has seven days, and you can assign numbers from 1 to 7 to represent them. But what’s the first day of the week?

According to ISO 8601, the standard on Data elements and interchange formats, Monday is the first day of the week, which doesn’t stop such countries as USA, Canada, and Australia consider Sunday as the first day of the week. Hence using just numbers from 1 to 7 for representing days may not be a good idea. Also, what if someone will assign the number 8 to the variable that store the day? We don’t want this to happen and using day names instead of the numbers makes our code more readable.

On the other hand, using numbers for storing days is more efficient than their names. So we want to have readability, the ability to restrict values to a limited set, and efficiency in storing data. This is where enums can help.

TypeScript has the enum keyword that can define a limited set of constants, and we can declare the new type for weekdays as follows:

Listing 4.1. Defining weekdays using enum
enum Weekdays {
  Monday = 1,
  Tuesday = 2,
  Wednesday = 3,
  Thursday = 4,
  Friday = 5,
  Saturday = 6,
  Sunday = 7
}

4.1.1  String enums

4.1.2  const enums

4.2  Generics

4.2.1  Understanding generics

4.2.2  Creating your own generic types

4.2.3  Creating generic functions

4.3  Summary