9 Using arrays, tuples, and enums
This chapter covers
- Restricting the types that an array can store
- Creating fixed-length arrays using tuples
- Using enums to group related values
- Using literal value types to specify a fixed set of acceptable values
- Creating a type alias to simplify working with complex type definitions
The examples so far in this part of the book have focused on primitive types, which has let me introduce the basic TypeScript features. In real projects, related data properties are grouped to create objects. In this chapter, I describe the TypeScript support for simple data structures, starting with arrays. Table 9.1 summarizes the chapter.
Table 9.1 Chapter summary (view table figure)
Problem |
Solution |
Listing |
---|---|---|
Restrict the range of types that an array can contain |
Apply a type annotation or allow the compiler to infer the types from the value used to initialize the array |
4–9 |
Define fixed-length arrays with specified types for each value |
Use a tuple |
10–14 |
Define variable-length arrays with specified types for each value |
Use a tuple with a rest element |
15 |
Refer to a collection of related values through a single name |
Use an enum |
16–25 |
Define a type that can be assigned only specific values |
Use a literal value type |
26–32 |
Avoid duplication when describing a complex type |
Use a type alias |
33 |
For quick reference, table 9.2 lists the TypeScript compiler options used in this chapter.