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

Generic Methods in Classes

Add methods with their own type parameters distinct from the class-level type parameters.

Generic Methods in Classes

You'll learn: How to add methods to a class that have their own independent type parameters, separate from the class's own generic types.

The Core Idea

A generic class like Box<T> has a type parameter that applies to the entire class. But sometimes you need a method within that class to work with a different type — one that's unrelated to the class-level T. Generic methods let you introduce brand-new type parameters just for that method's scope.

Think of it like this: your class might be a Container<Fruit>, but you still need a method that can compare any two things, not just fruits. The method gets its own type parameter for that specific job.

Syntax

class Box<T> {
  constructor(public value: T) {}

  // Method with its own type parameter U
  transform<U>(fn: (value: T) => U): Box<U> {
    return new Box(fn(this.value));
  }
}

const numberBox = new Box(42);
const stringBox = numberBox.transform(n => n.toString()); // Box<string>

Here, T is the class-level type (number), but U is independent—the method introduces it.

Why This Matters

Without method-level type parameters, you'd be stuck only working with T. Generic methods give you flexibility: the class maintains its type identity while individual methods can operate across different types.

class Storage<T> {
  private items: T[] = [];

  add(item: T): void {
    this.items.push(item);
  }

  // Generic method: converts items to a different type
  mapItems<U>(mapper: (item: T) => U): U[] {
    return this.items.map(mapper);
  }
}

Key Takeaway: Generic methods in classes have their own type parameters (<U>, <R>, etc.) that are distinct from and independent of the class's type parameters, enabling type-safe operations across multiple types within a single class.