11 Working with classes and interfaces

 

This chapter covers

  • Working with types for constructor functions
  • Defining classes with type annotations
  • Restricting access to class members with access controls
  • Simplifying classes by using the concise constructor syntax
  • Creating properties that can only be modified in the class constructor
  • Using accessors and auto-accessors
  • Understanding class inheritance
  • Using interfaces and abstract classes
  • Dynamically creating properties with index signatures

In this chapter, I describe the features that TypeScript provides for working with classes and introduce the interface feature, which provides an alternative approach to describing the shape of objects. Table 11.1 summarizes the chapter.

Table 11.1 Chapter summary (view table figure)

Problem

Solution

Listing

Create objects consistently

Use a constructor function or define a class

4–6, 17–19

Prevent access to properties and methods

Use the TypeScript access control keywords or JavaScript private fields

7-9

Prevent properties from being modified

Use the readonly keyword

10

Receive a constructor parameter and create an instance property in a single step

Use the concise constructor syntax

11

Separate data access from storage

Use accessors or auto-accessors

12–16

Define partial common functionality that will be inherited by subclasses

Define an abstract class

20, 21

Define a shape that classes can implement

Define an interface

12–27

Define a property dynamically

Use an index signature

28-32

11.1 Preparing for this chapter

11.2 Using constructor functions

11.3 Using classes

11.3.1 Using the access control keywords

11.3.2 Using JavaScript private fields

11.3.3 Defining read-only properties

11.3.4 Simplifying class constructors

11.3.5 Defining Accessors

11.3.6 Using auto-accessors

11.3.7 Using class inheritance

11.3.8 Using an abstract class

11.4 Using interfaces

11.4.2 Extending interfaces