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.