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

12.1 Preparing for this chapter

12.2 Understanding the problem solved by generic types

12.2.1 Adding support for another type

12.3 Creating generic classes

12.3.1 Understanding generic type arguments

12.3.2 Using different type arguments

12.3.3 Constraining generic type values

12.3.4 Defining multiple type parameters

12.3.5 Allowing the compiler to infer type arguments

12.3.6 Extending generic classes

12.3.7 Type guarding generic types

12.3.8 Defining a static method on a generic class

12.4 Defining generic interfaces

12.4.1 Extending generic interfaces

12.4.2 Implementing a generic interface

Summary