Generics

Generic Functions


Generics represent a type that won't be defined until the type is used in our code. We can use generics with functions. When we originally write the generic function, we might not know the type the generics represent, but when we use our function elsewhere in our code, the generics' types can be inferred from the usage. This makes it possible to write functions that accept different kinds of types but have the same implementation for each type.

These generic parameters are like variables; the more descriptive the name, the easier it is to understand what it's purpose is. We used **ItemType**, since our generic parameter represents the type of each item in the array. However, many libraries and authors use single-letter type names, like **T** or **U**, which can make generics seem more intimidating. Don't fret though. If you slow down and look closely, you should be able to see what is going on in the generic.


Generic Types



Generic options


  • **Default type → ** <T = DefaultType>
  • **Constrained type → ** <T extends ConstrainedType>

Advanced Constraints


  • Multiple generics
  • Second generic is constrained using extends
  • The constrained type is a keyof the other generic

Copyright 2023 © Borja Leiva

Made within London