Mastering TypeScript 3
上QQ阅读APP看书,第一时间看更新

Generics

Generics are a way of writing code that will deal with any type of object, but still maintain the object type integrity. So far, we have used interfaces, classes, and TypeScript's basic types to ensure strongly typed (and less error-prone) code in our samples. But what happens if a block of code needs to work with any type of object?

As an example, suppose we wanted to write some code that could iterate over an array of objects and return 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], return the string first,second,third. We could write some code that accepted values of type any, but this might introduce bugs in our code—remember S.F.I.A.T.? We want to ensure that all elements of the array are of the same type. This is where generics come in to play.