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

The Relationship Between Generics and Reusability

Understanding how generics enable writing one piece of code that works safely across many types.

The Relationship Between Generics and Reusability

You'll learn how generics transform single-purpose code into flexible, type-safe building blocks you can use across your entire codebase.

The Reusability Problem Without Generics

Imagine you need functions to get the first element from different types of arrays. Without generics, you'd write separate functions:

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

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

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

Every new type requires a new function. This violates the DRY principle (Don't Repeat Yourself) and becomes unmaintainable.

How Generics Enable Reusability

With generics, you write the logic once and let TypeScript adapt it to any type:

function getFirst<T>(arr: T[]): T {
  return arr[0];
}

const firstString = getFirst(["a", "b", "c"]); // string
const firstNumber = getFirst([1, 2, 3]);       // number
const firstBoolean = getFirst([true, false]);  // boolean

Same function, different types, full type safety. The type parameter T acts as a placeholder that gets filled in when you call the function.

The Reusability Principle

Generics create type-agnostic algorithms. You write the behavior once, and TypeScript ensures it works correctly with whatever types you pass. This is the essence of reusability: one implementation serving many contexts without sacrificing safety.

Think of generics like cookie cutters: the cutter's shape (your logic) stays the same, but it works on different dough types (your data types), producing perfectly shaped results every time.

Key Takeaway: Generics enable you to write one piece of code that safely handles many types, eliminating duplication and maximizing code reuse while preserving type safety.