Course contentsShow
← TypeScript
Lesson 525 of 1,79613. GenericsFree lesson

What Problem Do Generics Solve?

Understanding why we need a way to write type-safe code that works with multiple types without duplication.

What Problem Do Generics Solve?

You'll learn why TypeScript needs a mechanism to write reusable, type-safe code that works across multiple types without losing precision or duplicating logic.

The Duplication Problem

Imagine you need a function that returns the first element of an array. Without generics, you face an awkward choice:

Option 1: Write separate functions for each type

function firstString(arr: string[]): string {
  return arr[0];
}

function firstNumber(arr: number[]): number {
  return arr[0];
}

function firstBoolean(arr: boolean[]): boolean {
  return arr[0];
}

This creates massive duplication. The logic is identical, but you're forced to copy-paste for every type you support.

Option 2: Use any and lose all type safety

function first(arr: any[]): any {
  return arr[0];
}

const result = first([1, 2, 3]); // result is `any` — TypeScript knows nothing!

Now the function works with all types, but you've completely abandoned type safety. TypeScript can't help you anymore.

The Core Insight

You need a way to say: "This function works with arrays of some type, and it returns that same type" — without hardcoding what that type is.

The logic stays generic (works for any type), but the type relationship stays precise (input type matches output type).

Key Takeaway: Generics solve the tension between reusability and type safety, letting you write one implementation that preserves type information across different uses without duplication or resorting to any.