Getting Started with Generics

Discover how generics make TypeScript code reusable, precise, and safe across functions, types, interfaces, and classes.

We write a lot of functions that are meant to be flexible: loggers, wrappers, utilities, and state containers. In JavaScript, flexibility comes at the cost of safety. But in TypeScript, generics give us both—the ability to adapt to any type while still being type-safe.

Generics are how TypeScript lets us write reusable patterns without losing information about the types we’re working with. They let us define behavior once and apply it across many different types cleanly.

Let’s start by writing the simplest possible generic function.

Writing your first generic function

Here’s a basic identity function. It takes a value and returns it unchanged, but with full type fidelity.