13 Advanced generic types

 

This chapter covers

  • Using the JavaScript collection types with generic type parameters
  • Iterating over type-safe collections
  • Creating collection keys with index types
  • Transforming types with mappings
  • Using the built-in type mappings
  • Selecting generic types with conditional type expressions

In this chapter, I continue to describe the generic type features provided by TypeScript and focus on the advanced features. I explain how generic types can be used with collections and iterators, introduce the index types and type mapping features, and describe the most flexible of the generic type features: conditional types. Table 13.1 summarizes the chapter.

Table 13.1 Chapter summary (view table figure)

Problem

Solution

Listing

Use collection classes with type safety

Provide a generic type argument when creating the collection

3, 4

Use iterators with type safety

Use the interfaces that TypeScript provides that support generic type arguments

5–7

Define a type whose value can only be the name of a property

Use an index type query

8–14

Transform a type

Use a type mapping

15–22

Select types programmatically

Use conditional types

23–32

For quick reference, table 13.2 lists the TypeScript compiler options used in this chapter.

13.1 Preparing for this chapter

13.2 Using generic collections

13.3 Using generic iterators

13.3.1 Combining an iterable and an iterator

13.3.2 Creating an iterable class

13.4 Using index types

13.4.1 Using the index type query

13.4.2 Explicitly providing generic type parameters for index types

13.4.3 Using the indexed access operator

13.4.4 Using an index type for the collection<t> class

13.5 Using type mapping

13.5.1 Changing mapping names and types

13.5.2 Using a generic type parameter with a mapped type

13.5.3 Changing property optionality and mutability

13.5.4 Using the basic built-in mappings

13.5.5 Combining transformations in a single mapping

sitemap