What Are Generics?

Get an overview of generics and its naming conventions.

Genericshttps://www.typescriptlang.org/docs/handbook/2/generics.html are both powerful and also fairly simple once we understand them. Let’s start at the basics and build up from there as we work toward a full understanding of what generics are and how we can use them in our TypeScript code. In short, a generic in TypeScript allows us to write reusable code that works with more than one type. Generics act as placeholders for types, letting us write code that can adapt and enforce type consistency at compile-time. It’s not wrong to think of generics as variables, but just for our types.

Overview

Generics in TypeScript offer a means for creating reusable code components that work with a variety of types (rather than just one). As we mentioned, they can be thought of as variables—but for our types. Generics provide a way to create flexible structures that allow us to define the type later.

Let’s start with a simple linked list. A linked list node contains a value and then a link to the next node. We could start with something like this:

Get hands-on with 1400+ tech skills courses.