Back to Blog
November 20, 2023
6 min read

The Power of TypeScript Generics

TypeScriptJavaScriptProgramming

Generics are one of the most powerful features in TypeScript, allowing you to write code that is both flexible and type-safe.

Why Generics?

Without generics, we would often have to use any, which defeats the purpose of TypeScript. Generics allow us to capture the type of the argument in such a way that we can use it to denote what is being returned.

function identity<T>(arg: T): T {
  return arg;
}

By using <T>, we've captured the type the user provided (e.g., number), so that we can use that information later.