10 Working with objects

 

This chapter covers

  • Using shape types to describe objects
  • Making shape types easier to use with aliases
  • Creating unions of shape types
  • Guarding shape types
  • Creating and using type intersections

In this chapter, I describe the way that TypeScript deals with objects. As explained in chapters 3 and 4, JavaScript has a fluid and flexible approach to dealing with objects, and TypeScript aims to strike a balance between preventing the most common mistakes while allowing useful features to be preserved. This is a theme that is continued in chapter 11, where I describe the TypeScript support for using classes. Table 10.1 summarizes the chapter.

Table 10.1 Chapter summary (view table figure)

Problem

Solution

Listing

Describe an object to the TypeScript compiler

Use a shape type

4–6, 8

Describe irregular shape types

Use optional properties

7, 9, 10

Use the same shape to describe multiple objects

Use a type alias

11

Combine shape types

Use type unions or intersections

12, 13, 17–23

Type guard for object types

Check the properties defined by an object using the in keyword

14, 15

Reuse a type guard

Define a predicate function

16

For quick reference, table 10.2 lists the TypeScript compiler options used in this chapter.

10.1 Preparing for this chapter

10.2 Working with objects

10.2.1 Using object shape type annotations

10.2.2 Understanding how shape types fit

10.2.3 Using type aliases for shape types

10.2.4 Using shape type unions

10.2.5 Understanding union property types

10.2.6 Using type guards for objects

10.3 Using type intersections

10.3.1 Using intersections for data correlation

10.3.2 Understanding intersection merging

Summary