Generics
Generics, or, more specifically, generic syntax is a way of writing code that will work with a wide range of objects and primitives. As an example, suppose that we wanted to write a function that iterates over a given array of objects, and returns a concatenation of their values. So, given a list of numbers, say [1,2,3]
, it should return the string "1,2,3"
. Or, given a list of strings, say ["first", "second", "third"]
, it should return the string "first, second, third"
.
Using generics allows us to write type-safe code that can force each element of the array to be of the same type, and as such would not allow a mixed list of values to be sent through to our function, say [1,"second", true]
.
In this section of the chapter, we will introduce the generic code syntax, and explore the rules around what we can do with generic types.
Generic syntax
TypeScript uses an angled bracket syntax, and a type symbol...