12 Using generic types
This chapter covers
- Using generic type parameters as type placeholders
- Instantiating classes with generic type arguments
- Constraining generic type parameters
- Guarding generic types with predicate functions
- Defining interfaces with generic type parameters
Generic types are placeholders for types that are resolved when a class or function is used, allowing type-safe code to be written that can deal with a range of different types, such as collection classes. This is a concept that is more easily demonstrated than explained, so I start this chapter with an example of the problem that generic types solve and then describe the basic ways that generic types are used. In chapter 13, I describe the advanced generic type features that TypeScript provides. Table 12.1 summarizes the chapter.
Table 12.1 Chapter summary (view table figure)
Problem |
Solution |
Listing |
---|---|---|
Define a class or function that can safely operate on different types |
Define a generic type parameter |
6–8, 20, 21 |
Resolve a type for a generic type parameter |
Use a generic type argument when instantiating the class or invoking the function |
9–14 |
Extend a generic class |
Create a class that passes on, restricts, or fixes the generic type parameter inherited from the superclass |
15–17 |
Type guard a generic type |
Use a type predicate function |
18, 19 |
Describe a generic type without providing an implementation |
Define an interface with a generic type parameter |
22–26 |