Search⌘ K
AI Features

What Are Generics?

Explore how generics in TypeScript provide flexible placeholders for types, enabling you to write reusable and type-safe code. This lesson helps you understand the basics of generics, how to apply them with examples like linked lists, and how they improve code scalability and maintainability.

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