Chapter 4. Using 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

In chapter 2, we introduced unions, which allow you to create a custom type by combining several existing types. In this chapter, you’ll learn how to use enums—a way to create a new type based on a limited set of values.

We’ll also introduce generics, which allow you to place type constraints on class members, function parameters, or their return types.

4.1. Using enums

Enumerations (a.k.a. enums) allow you to create limited sets of named constants that have something in common. Such constants can be numbers or strings.

4.1.1. Numeric enums

A week has seven days, and you can assign the numbers 1 to 7 to represent them. But what’s the first day of the week?

4.2. Using generics

Summary

sitemap