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 ...

Get Essential TypeScript 5, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.