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.

9.1 Preparing for this chapter

9.2 Working with arrays

9.2.1 Using inferred typing for arrays

9.2.2 Avoiding problems with inferred array types

9.2.3 Avoiding problems with empty arrays

9.3 Working with tuples

9.3.1 Processing tuples

9.3.2 Using tuple types

9.3.3 Using tuples with optional elements

9.3.4 Defining tuples with rest elements

9.4 Using enums

9.4.1 Understanding how enums work

9.4.2 Using string enums

9.4.3 Understanding the limitations of enums

9.5 Using literal value types

9.5.1 Using literal value types in functions