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

Extending Generic Classes

Inherit from generic base classes while passing type arguments or adding new type parameters.

Extending Generic Classes

You'll learn how to create subclasses from generic base classes, either by locking in the type arguments or by adding your own type parameters.

The Core Idea

When you extend a generic class, you have two choices:

  1. Lock in the type parameters — decide exactly what types the base class should use
  2. Keep it generic — pass type parameters from your subclass to the base class, or even add new ones

Think of it like inheriting a template: you can either fill in the blanks now (concrete) or create a new template that still has blanks (still generic).

Locking In Type Parameters

You can extend a generic class and provide concrete types right away:

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

// Lock in the type parameter to string
class StringBox extends Box<string> {
  toUpperCase() {
    return this.value.toUpperCase();
  }
}

const box = new StringBox("hello");
console.log(box.toUpperCase()); // "HELLO"

Now StringBox is no longer generic — it's always a Box<string>.

Keeping It Generic

Alternatively, your subclass can remain generic and forward type parameters:

class Container<T> {
  constructor(public item: T) {}
}

// Pass U to the base class as T
class LabeledContainer<U> extends Container<U> {
  constructor(item: U, public label: string) {
    super(item);
  }
}

const labeled = new LabeledContainer(42, "count");
// labeled.item is number, label is string

You can even add additional type parameters that don't appear in the base class.

Key Takeaway: When extending generic classes, you decide whether to provide concrete types immediately or keep the subclass generic by forwarding or adding type parameters.