Generic Syntax
Learn how to write type-safe code using generics in TypeScript.
Generics, or, more specifically, the 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]
.
What is the generic syntax?
TypeScript uses an angled bracket syntax and a type symbol, or type substitute name, to indicate that we are using generic syntax.
In other words, to specify that the type named T
is being used within generic syntax, we will write <T>
to indicate that this code is substituting a normal type name with the symbol T
. Then, when we use a generic type, TypeScript will essentially substitute the type named T
with an actual type.
How to use generic syntax in TypeScript
This is best explained through some example code, as follows:
Get hands-on with 1400+ tech skills courses.