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 |