JavaScript and TypeScript course ยท Module 7: Advanced TypeScript

Generic Classes

9 min read ยท
In this lesson9

"Every enclosure in Jurassic Park must be adapted to a specific dinosaur species," explains Dr. Ellie Sattler, head of the botanical research department. "But despite the differences, all enclosures operate according to the same principles - entrance control, environmental condition monitoring, automated feeding systems. What distinguishes a velociraptor enclosure from a triceratops enclosure is not its structure, but its parameters."

Generic classes in TypeScript work the same way. They allow creating reusable components that can work with different data types while maintaining full type control. If generic functions showed us the basic idea of generics, generic classes demonstrate the full potential of this mechanism.

What Are Generic Classes?

Generic classes are class templates that can work with different data types. Just like generic functions, they use type parameters (e.g., <T>), but they allow using those parameters throughout the entire class - in fields, methods, and constructors.

Here's a simple generic class representing a dinosaur enclosure:

class DinosaurEnclosure<T> {
  private inhabitants: T[];

  constructor() {
    this.inhabitants = [];
  }

  addInhabitant(dino: T): void {
    this.inhabitants.push(dino);
    console.log("Added new inhabitant to enclosure!");
  }

  getInhabitants(): T[] {
    return [...this.inhabitants]; // We return a copy to avoid direct modification
  }

  countInhabitants(): number {
    return this.inhabitants.length;
  }
}

The above class can be used to create an enclosure for any type of dinosaurs:

// Dinosaur type definitions
interface Velociraptor {
  name: string;
  speed: number;
  clawLength: number;
}

interface Triceratops {
  name: string;
  hornLength: number;
  weight: number;
}

// Creating specialized enclosures
const raptorEnclosure = new DinosaurEnclosure<Velociraptor>();
const triceratopsEnclosure = new DinosaurEnclosure<Triceratops>();

// Adding inhabitants to enclosures
raptorEnclosure.addInhabitant({
  name: "Blue",
  speed: 70,
  clawLength: 15
});

triceratopsEnclosure.addInhabitant({
  name: "Topsy",
  hornLength: 80,
  weight: 9000
});

// Checking inhabitants
console.log(`Velociraptor count: ${raptorEnclosure.countInhabitants()}`);
console.log(`Triceratops count: ${triceratopsEnclosure.countInhabitants()}`);

// TypeScript ensures type safety
// This won't compile:
// raptorEnclosure.addInhabitant({
//   name: "Invalid",
//   hornLength: 50,
//   weight: 7000
// });

Classes with Multiple Type Parameters

Generic classes can use multiple type parameters, allowing even greater flexibility:

class ParkResearchLab<TSpecimen, TResult> {
  private specimens: TSpecimen[] = [];
  private results: Map<string, TResult> = new Map();

  addSpecimen(id: string, specimen: TSpecimen): void {
    this.specimens.push(specimen);
    console.log(`Added sample #${id}`);
  }

  recordResult(specimenId: string, result: TResult): void {
    this.results.set(specimenId, result);
    console.log(`Saved result for sample #${specimenId}`);
  }

  getResult(specimenId: string): TResult | undefined {
    return this.results.get(specimenId);
  }
}

// Example usage with specific types
interface BloodSample {
  dinosaurId: string;
  extractionDate: Date;
  volume: number;
}

interface BloodTestResult {
  oxygenLevel: number;
  whiteBloodCellCount: number;
  isHealthy: boolean;
}

const bloodLab = new ParkResearchLab<BloodSample, BloodTestResult>();

bloodLab.addSpecimen("BLD-001", {
  dinosaurId: "TREX-01",
  extractionDate: new Date(2023, 4, 15),
  volume: 250
});

bloodLab.recordResult("BLD-001", {
  oxygenLevel: 95,
  whiteBloodCellCount: 7500,
  isHealthy: true
});

const result = bloodLab.getResult("BLD-001");
console.log(`Blood test result: ${result?.isHealthy ? "Healthy" : "Needs attention"}`);

Extending Generic Classes

Generic classes can also be extended, allowing for more specialized implementations:

class MonitoredEnclosure<T> extends DinosaurEnclosure<T> {
  private lastCheckTime: Date | null = null;
  private securityLevel: "low" | "medium" | "high";

  constructor(securityLevel: "low" | "medium" | "high" = "medium") {
    super(); // Calling the base class constructor
    this.securityLevel = securityLevel;
  }

  performSecurityCheck(): void {
    this.lastCheckTime = new Date();
    console.log(`Security check performed at ${this.lastCheckTime.toLocaleTimeString()}`);
    console.log(`Security level: ${this.securityLevel}`);
    console.log(`Inhabitant count: ${this.countInhabitants()}`);
  }

  getLastCheckTime(): Date | null {
    return this.lastCheckTime;
  }

  upgradeSecurityLevel(): void {
    if (this.securityLevel === "low") {
      this.securityLevel = "medium";
    } else if (this.securityLevel === "medium") {
      this.securityLevel = "high";
    }
    console.log(`Updated security level to: ${this.securityLevel}`);
  }
}

// Using the extended class
const monitoredRaptorEnclosure = new MonitoredEnclosure<Velociraptor>("high");

monitoredRaptorEnclosure.addInhabitant({
  name: "Delta",
  speed: 65,
  clawLength: 14
});

monitoredRaptorEnclosure.performSecurityCheck();

Default Type Parameters

Just as functions can have default parameters, generic classes can have default types for their type parameters:

// Default dinosaur interface
interface DefaultDinosaur {
  name: string;
  species: string;
  age: number;
}

// Class with a default type parameter
class DinosaurTracker<T = DefaultDinosaur> {
  private trackedDinos: T[] = [];

  trackDinosaur(dino: T, location: string): void {
    this.trackedDinos.push(dino);
    console.log(`Started tracking dinosaur at location: ${location}`);
  }

  getTrackedCount(): number {
    return this.trackedDinos.length;
  }
}

// Usage with default type
const defaultTracker = new DinosaurTracker();
defaultTracker.trackDinosaur({
  name: "Rexy",
  species: "Tyrannosaurus Rex",
  age: 7
}, "Sector B");

// Usage with a custom type
interface AquaticDinosaur {
  name: string;
  underwaterSpeedKmh: number;
  maxDiveDepthMeters: number;
}

const aquaticTracker = new DinosaurTracker<AquaticDinosaur>();
aquaticTracker.trackDinosaur({
  name: "Nessie",
  underwaterSpeedKmh: 40,
  maxDiveDepthMeters: 500
}, "Central Lake");

Static Properties in Generic Classes

It's important to understand that type parameters in generic classes only apply to instance properties and methods. Static properties and methods are shared between all instances of the class, regardless of their type parameters:

class DinosaurRegistry<T> {
  private static totalRegisteredDinos: number = 0;
  private registeredDinos: T[] = [];

  registerDinosaur(dino: T): void {
    this.registeredDinos.push(dino);
    DinosaurRegistry.totalRegisteredDinos++;
    console.log(`Registered new dinosaur. Total: ${DinosaurRegistry.totalRegisteredDinos}`);
  }

  static getTotalRegisteredCount(): number {
    return DinosaurRegistry.totalRegisteredDinos;
  }
}

const rexRegistry = new DinosaurRegistry<Velociraptor>();
const triRegistry = new DinosaurRegistry<Triceratops>();

rexRegistry.registerDinosaur({
  name: "Charlie",
  speed: 68,
  clawLength: 12
});

triRegistry.registerDinosaur({
  name: "Cera",
  hornLength: 75,
  weight: 8500
});

console.log(`Total registered dinosaurs: ${DinosaurRegistry.getTotalRegisteredCount()}`); // 2

In this example, the static variable totalRegisteredDinos is shared across all instances of DinosaurRegistry, regardless of their type parameters.

Generic Classes and Generic Interfaces

Generic classes often work with generic interfaces, creating a comprehensive type system:

// Generic interface
interface Repository<T> {
  add(item: T): void;
  getById(id: string): T | undefined;
  getAll(): T[];
  update(id: string, item: T): boolean;
  delete(id: string): boolean;
}

// Implementation of a generic class conforming to a generic interface
class DinosaurRepository<T extends { id: string }> implements Repository<T> {
  private items: Map<string, T> = new Map();

  add(item: T): void {
    this.items.set(item.id, item);
  }

  getById(id: string): T | undefined {
    return this.items.get(id);
  }

  getAll(): T[] {
    return Array.from(this.items.values());
  }

  update(id: string, item: T): boolean {
    if (this.items.has(id)) {
      this.items.set(id, item);
      return true;
    }
    return false;
  }

  delete(id: string): boolean {
    return this.items.delete(id);
  }
}

// Using the repository with a specific type
interface DinosaurRecord {
  id: string;
  name: string;
  species: string;
  dateOfBirth: Date;
}

const dinoRepo = new DinosaurRepository<DinosaurRecord>();

dinoRepo.add({
  id: "DINO-001",
  name: "Rex",
  species: "Tyrannosaurus",
  dateOfBirth: new Date(2018, 3, 10)
});

const rex = dinoRepo.getById("DINO-001");
console.log(`Found dinosaur: ${rex?.name}, Species: ${rex?.species}`);

Practical Example: Jurassic Park Asset Management System

Let's now expand our knowledge of generic classes by implementing a comprehensive asset management system for Jurassic Park:

// Basic interface for all park assets
interface ParkAsset {
  id: string;
  name: string;
  status: "operational" | "maintenance" | "offline";
  lastUpdated: Date;
}

// Different asset types
interface Vehicle extends ParkAsset {
  type: "jeep" | "boat" | "helicopter";
  passengerCapacity: number;
  currentFuel: number;
}

interface Facility extends ParkAsset {
  type: "visitor" | "research" | "security";
  location: { x: number, y: number };
  capacity: number;
}

interface PowerSystem extends ParkAsset {
  type: "main" | "backup" | "sector";
  outputCapacity: number;
  currentLoad: number;
}

// Generic interface for asset management
interface AssetManager<T extends ParkAsset> {
  registerAsset(asset: T): void;
  getAsset(id: string): T | undefined;
  updateStatus(id: string, status: T["status"]): boolean;
  getOperationalAssets(): T[];
}

// Implementation of a generic asset management class
class JurassicParkAssetManager<T extends ParkAsset> implements AssetManager<T> {
  private assets: Map<string, T> = new Map();
  private statusChangeLog: { assetId: string, oldStatus: string, newStatus: string, timestamp: Date }[] = [];

  constructor(private assetType: string) {
    console.log(`Initialized asset management system for type: ${assetType}`);
  }

  registerAsset(asset: T): void {
    if (this.assets.has(asset.id)) {
      throw new Error(`Asset with ID ${asset.id} already exists`);
    }

    this.assets.set(asset.id, {
      ...asset,
      lastUpdated: new Date()
    });

    console.log(`Registered new asset: ${asset.name} (ID: ${asset.id})`);
  }

  getAsset(id: string): T | undefined {
    return this.assets.get(id);
  }

  updateStatus(id: string, status: T["status"]): boolean {
    const asset = this.assets.get(id);

    if (!asset) {
      console.warn(`Asset with ID ${id} not found`);
      return false;
    }

    const oldStatus = asset.status;

    // Status update
    const updatedAsset = {
      ...asset,
      status,
      lastUpdated: new Date()
    };

    this.assets.set(id, updatedAsset);

    // Logging the change
    this.statusChangeLog.push({
      assetId: id,
      oldStatus,
      newStatus: status,
      timestamp: new Date()
    });

    console.log(`Updated status of asset ${asset.name} from "${oldStatus}" to "${status}"`);
    return true;
  }

  getOperationalAssets(): T[] {
    return Array.from(this.assets.values())
      .filter(asset => asset.status === "operational");
  }

  getStatusChangeHistory(id?: string): typeof this.statusChangeLog {
    if (id) {
      return this.statusChangeLog.filter(log => log.assetId === id);
    }
    return [...this.statusChangeLog];
  }

  generateReport(): string {
    const totalAssets = this.assets.size;
    const operational = this.getOperationalAssets().length;
    const maintenance = Array.from(this.assets.values())
      .filter(asset => asset.status === "maintenance").length;
    const offline = Array.from(this.assets.values())
      .filter(asset => asset.status === "offline").length;

    return `
ASSET STATUS REPORT: ${this.assetType.toUpperCase()}
======================================
Total count: ${totalAssets}
Operational: ${operational} (${Math.round(operational / totalAssets * 100)}%)
In maintenance: ${maintenance} (${Math.round(maintenance / totalAssets * 100)}%)
Offline: ${offline} (${Math.round(offline / totalAssets * 100)}%)
======================================
Generated: ${new Date().toLocaleString()}
    `;
  }
}

// Using the asset management system with different types
const vehicleManager = new JurassicParkAssetManager<Vehicle>("Vehicles");
const facilityManager = new JurassicParkAssetManager<Facility>("Facilities");
const powerManager = new JurassicParkAssetManager<PowerSystem>("Power");

// Registering sample assets
vehicleManager.registerAsset({
  id: "VEH-001",
  name: "Explorer 04",
  status: "operational",
  lastUpdated: new Date(),
  type: "jeep",
  passengerCapacity: 5,
  currentFuel: 75
});

vehicleManager.registerAsset({
  id: "VEH-002",
  name: "Explorer 05",
  status: "maintenance",
  lastUpdated: new Date(),
  type: "jeep",
  passengerCapacity: 5,
  currentFuel: 30
});

facilityManager.registerAsset({
  id: "FAC-001",
  name: "Visitor Center",
  status: "operational",
  lastUpdated: new Date(),
  type: "visitor",
  location: { x: 100, y: 200 },
  capacity: 200
});

powerManager.registerAsset({
  id: "PWR-001",
  name: "Main Power Grid",
  status: "operational",
  lastUpdated: new Date(),
  type: "main",
  outputCapacity: 10000,
  currentLoad: 6500
});

// Simulating failures and status updates
vehicleManager.updateStatus("VEH-001", "maintenance");
powerManager.updateStatus("PWR-001", "offline");
facilityManager.updateStatus("FAC-001", "maintenance");

// After the fix
setTimeout(() => {
  vehicleManager.updateStatus("VEH-001", "operational");
  powerManager.updateStatus("PWR-001", "operational");
  facilityManager.updateStatus("FAC-001", "operational");

  // Generating reports
  console.log(vehicleManager.generateReport());
  console.log(powerManager.generateReport());

  // Status change history
  console.log("Main power status change history:");
  console.log(powerManager.getStatusChangeHistory("PWR-001"));
}, 3000);

When to Use Generic Classes?

Generic classes are especially useful in the following situations:

  1. Data collections and containers - when you need to store and manage elements of different types
  2. Services and repositories - when implementing design patterns that should work with different data types
  3. Reusable components - when you want to create flexible components that can be used in different contexts
  4. Abstractions at different levels - when you want to define class hierarchies that can be specialized for different types

Summary

Generic classes are a powerful tool in TypeScript that allows creating flexible, type-safe code. They provide an excellent balance between reusability and type safety, enabling the creation of components that:

  • Can work with different data types
  • Maintain full type information
  • Provide compiler and IDE support (suggestions, type verification)
  • Are readable and understandable for other programmers

Just like in Jurassic Park, where infrastructure must be flexible to accommodate different dinosaur species, generic classes allow us to build systems that are both flexible and safe - the perfect combination for modern software development.

In the next exercise, we'll look at how we can further refine our generics using generic constraints to ensure that our generic classes and functions only work with types that meet specific requirements.

Code for this lesson: index.ts
// Generic classes - Jurassic Park
console.log("=== GENERIC CLASSES ===\n");

// ===========================================
// 1. GenericRepository<T> - a data repository
// ===========================================

interface Identifiable {
  id: number;
  name: string;
}

class GenericRepository<T extends Identifiable> {
  private items: Map<number, T> = new Map();
  private label: string;

  constructor(label: string) {
    this.label = label;
  }

  add(item: T): void {
    this.items.set(item.id, item);
  }

  getById(id: number): T | undefined {
    return this.items.get(id);
  }

  getAll(): T[] {
    return Array.from(this.items.values());
  }

  remove(id: number): boolean {
    return this.items.delete(id);
  }

  count(): number {
    return this.items.size;
  }

  find(predicate: (item: T) => boolean): T[] {
    return this.getAll().filter(predicate);
  }

  toString(): string {
    return `[${this.label}] ${this.count()} records`;
  }
}

// ===========================================
// 2. Collection<T> - a collection with iteration
// ===========================================

class Collection<T> {
  private elements: T[] = [];

  add(...items: T[]): Collection<T> {
    this.elements.push(...items);
    return this; // Fluent API
  }

  first(): T | undefined {
    return this.elements[0];
  }

  last(): T | undefined {
    return this.elements[this.elements.length - 1];
  }

  map<U>(fn: (item: T) => U): Collection<U> {
    const result = new Collection<U>();
    result.add(...this.elements.map(fn));
    return result;
  }

  filter(fn: (item: T) => boolean): Collection<T> {
    const result = new Collection<T>();
    result.add(...this.elements.filter(fn));
    return result;
  }

  toArray(): T[] {
    return [...this.elements];
  }

  get size(): number {
    return this.elements.length;
  }
}

// ===========================================
// 3. Pair<A, B> - a pair of values
// ===========================================

class Pair<A, B> {
  constructor(
    public readonly first: A,
    public readonly second: B
  ) {}

  swap(): Pair<B, A> {
    return new Pair(this.second, this.first);
  }

  toString(): string {
    return `(${this.first}, ${this.second})`;
  }
}

// ===========================================
// Test
// ===========================================

// --- GenericRepository ---
interface Dinosaur {
  id: number;
  name: string;
  species: string;
  weight: number;
}

interface Enclosure {
  id: number;
  name: string;
  capacity: number;
}

const dinoRepo = new GenericRepository<Dinosaur>("Dinosaurs");
dinoRepo.add({ id: 1, name: "Rexy", species: "T-Rex", weight: 8000 });
dinoRepo.add({ id: 2, name: "Blue", species: "Velociraptor", weight: 15 });
dinoRepo.add({ id: 3, name: "Cera", species: "Triceratops", weight: 6000 });

const encRepo = new GenericRepository<Enclosure>("Enclosures");
encRepo.add({ id: 101, name: "T-Rex Zone", capacity: 2 });
encRepo.add({ id: 102, name: "Raptor Valley", capacity: 6 });

console.log(dinoRepo.toString());
console.log(encRepo.toString());

console.log("\nDinosaur #2:", dinoRepo.getById(2)?.name);
console.log("Heavy (>1000kg):", dinoRepo.find(d => d.weight > 1000).map(d => d.name).join(", "));

// --- Collection ---
console.log("\n--- Collection with a fluent API ---");
const names = new Collection<string>()
  .add("Rexy", "Blue", "Delta", "Charlie", "Cera")
  .filter(n => n.length <= 4)
  .map(n => n.toUpperCase());

console.log("Short names:", names.toArray().join(", "));
console.log("First:", names.first());
console.log("Last:", names.last());

// --- Pair ---
console.log("\n--- Pair ---");
const dinoEnclosure = new Pair<string, string>("Rexy", "T-Rex Zone");
console.log("Pair:", dinoEnclosure.toString());

const swapped = dinoEnclosure.swap();
console.log("Swapped:", swapped.toString());

const idWeight = new Pair<number, number>(1, 8000);
console.log("ID-Weight:", idWeight.toString());

console.log("\nGeneric classes guarantee type safety!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. When is it better to use a generic <T> instead of a union type (string | number)?

Hands-on tasks in the game

  • Code editor

    Create a generic data repository for the park

  • Vertical ordering

    Order the access modifiers from most restrictive to broadest:

  1. QuestionGenerics vs Union Types
  2. Coding taskGeneric Classes
  3. Put in orderAccess Modifier Visibility Scope

Useful articles