Search⌘ K
AI Features

Generic Syntax

Explore how TypeScript's generic syntax allows you to create reusable, type-safe code that works with a variety of data types. Understand explicit type specification, type inference, and using multiple generic types in functions to ensure stronger type safety in your applications.

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