JavaScript and TypeScript course ยท Module 7: Advanced TypeScript

Static and Abstract Properties

23 min read ยท
In this lesson4

"In Jurassic Park, we have protocols and standards that apply to all objects of a given class," explains Dr. Henry Wu, the park's chief geneticist. "For example, all our dinosaur enclosures follow the same security procedure, regardless of which specific enclosure we're considering. On the other hand, every dinosaur species has its own unique DNA pattern, but we all know that DNA must exist - even if the details differ between species."

In object-oriented programming, TypeScript offers two powerful concepts that reflect these ideas:

  • Static properties and methods - shared by all instances of a class
  • Abstract properties and methods - must be implemented by inheriting classes

In this exercise, we will dive deep into these concepts by creating an advanced genetics and security protocol management system for Jurassic Park.

Static Properties and Methods

Static elements in a class belong to the class itself, not to its instances. This means:

  • There is only one copy of each static property, regardless of the number of created instances
  • Access to static properties is through the class name, not through an instance
  • Static methods can be called directly on the class

Basic Usage of Static Elements

Let's see how static elements can be used in the context of Jurassic Park:

class SecurityProtocol {
  // Static property - shared by all instances
  static readonly LEVEL_CRITICAL: number = 5;
  static readonly LEVEL_HIGH: number = 4;
  static readonly LEVEL_MEDIUM: number = 3;
  static readonly LEVEL_LOW: number = 2;
  static readonly LEVEL_MINIMAL: number = 1;

  // Static property storing the current global park threat level
  private static _currentThreatLevel: number = SecurityProtocol.LEVEL_LOW;

  // Instance properties
  private readonly area: string;
  private localThreatLevel: number;

  constructor(area: string) {
    this.area = area;
    this.localThreatLevel = SecurityProtocol._currentThreatLevel;
    console.log(`Created security protocol for area: ${area}`);
  }

  // Static method accessible directly on the class
  static raiseGlobalThreatLevel(): void {
    if (this._currentThreatLevel < this.LEVEL_CRITICAL) {
      this._currentThreatLevel++;
      console.log(`WARNING: Raised global threat level to ${this._currentThreatLevel}`);

      // Calling another static method
      this.notifyAboutThreatLevel();
    } else {
      console.log("WARNING: Maximum threat level already reached!");
    }
  }

  // Another static method
  static lowerGlobalThreatLevel(): void {
    if (this._currentThreatLevel > this.LEVEL_MINIMAL) {
      this._currentThreatLevel--;
      console.log(`Lowered global threat level to ${this._currentThreatLevel}`);
    } else {
      console.log("Threat level is already at minimum.");
    }
  }

  // Static getter
  static get currentThreatLevel(): number {
    return this._currentThreatLevel;
  }

  // Private static method
  private static notifyAboutThreatLevel(): void {
    console.log(`Notification: Current park threat level: ${this._currentThreatLevel}`);
  }

  // Instance method using static properties
  updateLocalThreatLevel(): void {
    // Updating the local level based on the global level
    this.localThreatLevel = SecurityProtocol._currentThreatLevel;
    console.log(`Area ${this.area}: updated threat level to ${this.localThreatLevel}`);
  }

  get securityStatus(): string {
    const levels = [
      "UNKNOWN",
      "MINIMAL",
      "LOW",
      "MEDIUM",
      "HIGH",
      "CRITICAL"
    ];

    return `Area: ${this.area}, Threat level: ${levels[this.localThreatLevel]}`;
  }
}

// Using static properties and methods - without creating instances!
console.log("Default threat level:", SecurityProtocol.currentThreatLevel);

// Calling a static method directly on the class
SecurityProtocol.raiseGlobalThreatLevel();
SecurityProtocol.raiseGlobalThreatLevel();

// Creating instances of the class
const centralProtocol = new SecurityProtocol("Operations Center");
const enclosureProtocol = new SecurityProtocol("T-Rex Enclosure");

// Displaying the security status
console.log(centralProtocol.securityStatus);
console.log(enclosureProtocol.securityStatus);

// Raising the global threat level again
SecurityProtocol.raiseGlobalThreatLevel();

// Updating local threat levels
centralProtocol.updateLocalThreatLevel();
enclosureProtocol.updateLocalThreatLevel();

// Checking updated statuses
console.log(centralProtocol.securityStatus);
console.log(enclosureProtocol.securityStatus);

In the above example:

  1. Threat level constants are static properties, accessible directly through the class
  2. The static property _currentThreatLevel is shared across all instances
  3. Static methods can modify static properties and call other static methods
  4. Class instances can update their internal states based on static properties

When to Use Static Elements

Static elements are especially useful in the following cases:

  1. Constants and configuration - Values that remain unchanged for all instances of a class
  2. Global state - When we need a value shared by all instances
  3. Utility methods - Helper functions that don't require instance state
  4. Factory methods - Alternative ways to create class instances

Here's a more elaborate example showing different uses of static elements:

class GeneticRegistry {
  // Static constants
  static readonly NUCLEOTIDE_BASE = ["A", "C", "G", "T"];
  static readonly MIN_DNA_LENGTH = 1000000;

  // Global state
  private static _registeredSpeciesCount: number = 0;
  private static _speciesRegistrations: Map<string, string> = new Map();

  // Instance properties
  private id: string;
  private dnaSequence: string;
  private name: string;

  constructor(name: string, dnaSequence: string) {
    if (dnaSequence.length < GeneticRegistry.MIN_DNA_LENGTH) {
      throw new Error(`DNA sequence is too short. Minimum required: ${GeneticRegistry.MIN_DNA_LENGTH} base pairs.`);
    }

    this.name = name;
    this.dnaSequence = dnaSequence;
    this.id = GeneticRegistry.generateId(name);

    // Registering a new species
    GeneticRegistry._speciesRegistrations.set(this.id, name);
    GeneticRegistry._registeredSpeciesCount++;
  }

  // Utility method - creates an ID based on name
  private static generateId(name: string): string {
    const timestamp = Date.now();
    const cleanName = name.toLowerCase().replace(/[^a-z0-9]/g, "");
    return `DNA-${cleanName}-${timestamp}`;
  }

  // Factory method - creates an instance with random DNA
  static createTestSpecies(name: string): GeneticRegistry {
    const dnaLength = this.MIN_DNA_LENGTH + Math.floor(Math.random() * 500000);
    let sequence = "";

    for (let i = 0; i < dnaLength; i++) {
      const randomIndex = Math.floor(Math.random() * this.NUCLEOTIDE_BASE.length);
      sequence += this.NUCLEOTIDE_BASE[randomIndex];
    }

    return new GeneticRegistry(name, sequence);
  }

  // Utility method - verifies the correctness of a DNA sequence
  static verifySequence(sequence: string): boolean {
    if (sequence.length < this.MIN_DNA_LENGTH) return false;

    // Checks if the sequence contains only allowed nucleotides
    for (const nucleotide of sequence) {
      if (!this.NUCLEOTIDE_BASE.includes(nucleotide)) {
        return false;
      }
    }

    return true;
  }

  // Getter for the static property
  static get registeredSpeciesCount(): number {
    return this._registeredSpeciesCount;
  }

  // Static method returning all registered species
  static getAllSpecies(): string[] {
    return Array.from(this._speciesRegistrations.values());
  }

  // Instance method using static fields
  analyzeSequence(): { proportions: Record<string, number>, length: number } {
    const proportions: Record<string, number> = {};

    // Initializing counters for each nucleotide
    GeneticRegistry.NUCLEOTIDE_BASE.forEach(n => {
      proportions[n] = 0;
    });

    // Counting nucleotides
    for (const nucleotide of this.dnaSequence) {
      proportions[nucleotide]++;
    }

    // Converting to percentages
    GeneticRegistry.NUCLEOTIDE_BASE.forEach(n => {
      proportions[n] = Number((proportions[n] / this.dnaSequence.length * 100).toFixed(2));
    });

    return {
      proportions,
      length: this.dnaSequence.length
    };
  }

  // Instance getters
  get identifier(): string {
    return this.id;
  }

  get speciesName(): string {
    return this.name;
  }
}

// Using static methods and properties
console.log("Minimum DNA length:", GeneticRegistry.MIN_DNA_LENGTH);
console.log("Available nucleotides:", GeneticRegistry.NUCLEOTIDE_BASE.join(", "));

// Verifying a sample sequence
const exampleSequence = "ACGTACGTACGT".repeat(100000); // Repeating to reach min. length
console.log("Sequence verification:", GeneticRegistry.verifySequence(exampleSequence));

// Creating instances using the factory method
const trex = GeneticRegistry.createTestSpecies("Tyrannosaurus Rex");
const raptor = GeneticRegistry.createTestSpecies("Velociraptor");
const trike = GeneticRegistry.createTestSpecies("Triceratops");

// Checking how many species have been registered
console.log("Number of registered species:", GeneticRegistry.registeredSpeciesCount);
console.log("Species list:", GeneticRegistry.getAllSpecies());

// Using instance methods
const trexAnalysis = trex.analyzeSequence();
console.log(`Analysis of ${trex.speciesName} (ID: ${trex.identifier}):`);
console.log(`Sequence length: ${trexAnalysis.length} base pairs`);
console.log("Nucleotide proportions:", trexAnalysis.proportions);

This example demonstrates:

  1. Using static constants (NUCLEOTIDE_BASE, MIN_DNA_LENGTH)
  2. Global state tracking the number and registration of species
  3. Static utility methods like verifySequence and generateId
  4. A factory method createTestSpecies creating instances with random data
  5. How instance methods can use static properties

Abstract Classes and Methods

Abstract classes in TypeScript define a template that must be implemented by inheriting classes. You cannot create an instance of an abstract class directly - it serves as a base "blueprint" for other classes.

Abstract methods, defined in an abstract class, must be implemented by inheriting classes. They define a contract specifying which methods must be available, but they don't contain their own implementation.

Abstract Class Basics

Let's see how to use abstract classes in the context of Jurassic Park:

// Abstract base class for all dinosaurs
abstract class Dinosaur {
  // Properties common to all dinosaurs
  private _id: string;
  protected _name: string;
  protected _species: string;
  protected _age: number;
  protected _weight: number;

  constructor(id: string, name: string, species: string, age: number, weight: number) {
    this._id = id;
    this._name = name;
    this._species = species;
    this._age = age;
    this._weight = weight;
  }

  // Getters
  get id(): string { return this._id; }
  get name(): string { return this._name; }
  get species(): string { return this._species; }
  get age(): number { return this._age; }
  get weight(): number { return this._weight; }

  // Methods implemented in all derived classes
  abstract calculateCaloricNeeds(): number;
  abstract determineThreatLevel(): number;

  // Abstract property - must be implemented in derived classes
  abstract get dietType(): string;

  // Concrete method (not abstract) - available in all derived classes
  getBasicData(): string {
    return `${this._name} (${this._species}) - ID: ${this._id}, Age: ${this._age} years, Weight: ${this._weight} kg`;
  }

  // Method using abstract methods
  generateDinosaurReport(): string {
    const calories = this.calculateCaloricNeeds();
    const threatLevel = this.determineThreatLevel();

    return `
=== DINOSAUR REPORT ===
${this.getBasicData()}
Diet type: ${this.dietType}
Daily caloric requirement: ${calories} kcal
Threat level: ${threatLevel}/10
======================
    `;
  }
}

// Class inheriting from the abstract class
class PredatoryDinosaur extends Dinosaur {
  private _biteForce: number;
  private _runSpeed: number;

  constructor(
    id: string,
    name: string,
    species: string,
    age: number,
    weight: number,
    biteForce: number,
    runSpeed: number
  ) {
    super(id, name, species, age, weight);
    this._biteForce = biteForce;
    this._runSpeed = runSpeed;
  }

  // Getters
  get biteForce(): number { return this._biteForce; }
  get runSpeed(): number { return this._runSpeed; }

  // Implementation of abstract property
  get dietType(): string {
    return "carnivore";
  }

  // Implementations of abstract methods
  calculateCaloricNeeds(): number {
    // For predators we use a complex formula
    return Math.round(this._weight * 0.6 * (this._runSpeed * 0.2));
  }

  determineThreatLevel(): number {
    // Threat level depends on bite force, speed, and weight
    const base = (this._biteForce * 0.7 + this._runSpeed * 0.3) / 100;
    return Math.min(10, Math.max(1, Math.round(base)));
  }

  // Method specific to predators
  hunt(): string {
    return `${this._name} hunts at speed ${this._runSpeed} km/h and bite force ${this._biteForce} PSI`;
  }
}

// Another inheriting class
class HerbivorousDinosaur extends Dinosaur {
  private _neckLength: number;
  private _armorType: "none" | "light" | "medium" | "heavy";

  constructor(
    id: string,
    name: string,
    species: string,
    age: number,
    weight: number,
    neckLength: number,
    armorType: "none" | "light" | "medium" | "heavy"
  ) {
    super(id, name, species, age, weight);
    this._neckLength = neckLength;
    this._armorType = armorType;
  }

  // Getters
  get neckLength(): number { return this._neckLength; }
  get armorType(): string { return this._armorType; }

  // Implementation of abstract property
  get dietType(): string {
    return "herbivorous";
  }

  // Implementations of abstract methods
  calculateCaloricNeeds(): number {
    // For herbivores we use a simpler formula - they need more calories per kilogram
    return Math.round(this._weight * 0.8);
  }

  determineThreatLevel(): number {
    // Threat level is lower for herbivores, but depends on weight and armor type
    let base = this._weight / 1000;

    // Modifier dependent on armor
    const armorModifiers = {
      "none": 0,
      "light": 1,
      "medium": 2,
      "heavy": 3
    };

    base += armorModifiers[this._armorType];

    return Math.min(7, Math.max(1, Math.round(base))); // Max. 7 for herbivores
  }

  // Method specific to herbivores
  graze(): string {
    const reachHeight = this._neckLength > 2 ? "tall" : "low";
    return `${this._name} is grazing, eating plants from ${reachHeight} tree sections`;
  }
}

// We cannot create an instance of an abstract class
// const invalid = new Dinosaur("ID", "Name", "Species", 1, 100); // Error!

// Creating instances of derived classes
const trex = new PredatoryDinosaur("T-REX-1", "Rex", "Tyrannosaurus", 8, 7000, 12800, 32);
const stegosaurus = new HerbivorousDinosaur("STEG-1", "Spike", "Stegosaurus", 12, 5000, 1.2, "heavy");
const diplodocus = new HerbivorousDinosaur("DIPL-1", "Dippy", "Diplodocus", 15, 16000, 6.5, "none");

// Using methods implemented in derived classes
console.log(trex.generateDinosaurReport());
console.log(stegosaurus.generateDinosaurReport());
console.log(diplodocus.generateDinosaurReport());

// Using methods specific to a given class
console.log(trex.hunt());
console.log(stegosaurus.graze());

// For both types of dinosaurs we can use base class methods
console.log(trex.getBasicData());
console.log(diplodocus.getBasicData());

In the above example:

  1. Dinosaur is an abstract class containing shared properties and methods
  2. Abstract methods calculateCaloricNeeds() and determineThreatLevel() must be implemented by inheriting classes
  3. The abstract property dietType must be defined in derived classes
  4. Classes PredatoryDinosaur and HerbivorousDinosaur implement the abstract methods and properties
  5. You cannot create an instance of the Dinosaur class directly

Applications of Abstract Classes and Methods

Abstract classes are especially useful in the following cases:

  1. Defining a common interface - Specifying a consistent set of methods for a group of related classes
  2. Sharing code - Providing common implementation for groups of classes
  3. Enforcing a contract - Guaranteeing that all derived classes will implement the required methods
  4. Creating type hierarchies - Building complex relationships between types

Let's see a more advanced example combining abstract classes and methods with static elements in a security protocol management system for Jurassic Park:

// Helper types
type AlertLevel = "normal" | "elevated" | "high" | "critical";
type SystemStatus = "active" | "inactive" | "under_maintenance" | "failure";

// Interface for monitoring systems
interface MonitoringSystem {
  startMonitoring(): void;
  stopMonitoring(): void;
  getCurrentStatus(): SystemStatus;
}

// Abstract base class for all security systems
abstract class SecuritySystem implements MonitoringSystem {
  // Static properties - for all security systems
  private static _parkAlertLevel: AlertLevel = "normal";
  private static _activeSystems: Set<string> = new Set();
  private static _incidents: Array<{date: Date, systemType: string, location: string, description: string}> = [];

  // Regular properties
  protected _id: string;
  protected _location: string;
  protected _status: SystemStatus;
  protected _isMonitored: boolean;
  protected _reviewDate: Date;

  constructor(id: string, location: string) {
    this._id = id;
    this._location = location;
    this._status = "inactive";
    this._isMonitored = false;
    this._reviewDate = new Date();

    // System registration
    SecuritySystem.registerSystem(id, this.constructor.name);
  }

  // Static methods
  static registerSystem(id: string, systemType: string): void {
    console.log(`Registered new security system: ${systemType} (ID: ${id})`);
  }

  static reportIncident(systemType: string, location: string, description: string): void {
    const incident = {
      date: new Date(),
      systemType,
      location,
      description
    };

    this._incidents.push(incident);
    console.log(`ALERT: Incident reported at location ${location}: ${description}`);

    // Automatically raising the alert level
    if (this._parkAlertLevel === "normal") {
      this.changeAlertLevel("elevated");
    } else if (this._parkAlertLevel === "elevated") {
      this.changeAlertLevel("high");
    } else if (this._parkAlertLevel === "high") {
      this.changeAlertLevel("critical");
    }
  }

  static changeAlertLevel(newLevel: AlertLevel): void {
    this._parkAlertLevel = newLevel;
    console.log(`WARNING: Changed park alert level to: ${newLevel.toUpperCase()}`);
  }

  static get alertLevel(): AlertLevel {
    return this._parkAlertLevel;
  }

  static get recentIncidents(): Array<{date: Date, systemType: string, location: string, description: string}> {
    // Returning the 5 most recent incidents
    return [...this._incidents].slice(-5);
  }

  // Instance getters
  get id(): string { return this._id; }
  get location(): string { return this._location; }
  get status(): SystemStatus { return this._status; }

  // Implementation of MonitoringSystem interface
  startMonitoring(): void {
    this._isMonitored = true;
    SecuritySystem._activeSystems.add(this._id);
    console.log(`Monitoring started for system ${this.constructor.name} at location ${this._location}`);
  }

  stopMonitoring(): void {
    this._isMonitored = false;
    SecuritySystem._activeSystems.delete(this._id);
    console.log(`Monitoring stopped for system ${this.constructor.name} at location ${this._location}`);
  }

  getCurrentStatus(): SystemStatus {
    return this._status;
  }

  // Abstract methods that must be implemented
  abstract start(): void;
  abstract stop(): void;
  abstract performReview(): void;

  // Abstract properties
  abstract get systemType(): string;
  abstract get alarmPriorityLevel(): number; // 1-10

  // Method using abstract properties and methods
  generateStatusReport(): string {
    return `
=== SECURITY SYSTEM REPORT ===
ID: ${this._id}
Type: ${this.systemType}
Location: ${this._location}
Status: ${this._status}
Monitored: ${this._isMonitored ? "YES" : "NO"}
Alarm priority: ${this.alarmPriorityLevel}/10
Last review: ${this._reviewDate.toLocaleDateString()}
Global alert level: ${SecuritySystem._parkAlertLevel.toUpperCase()}
=================================
    `;
  }
}

// Derived class - Electric Fence System
class ElectricFenceSystem extends SecuritySystem {
  private _voltage: number; // in volts
  private _fenceLength: number; // in meters
  private _securityType: "standard" | "reinforced" | "ultra-reinforced";

  constructor(
    id: string,
    location: string,
    fenceLength: number,
    securityType: "standard" | "reinforced" | "ultra-reinforced"
  ) {
    super(id, location);
    this._voltage = 0;
    this._fenceLength = fenceLength;
    this._securityType = securityType;
  }

  // Implementation of abstract properties
  get systemType(): string {
    return "Electric Fence";
  }

  get alarmPriorityLevel(): number {
    // Priority depends on the security type
    const base = this._securityType === "standard" ? 7 :
                  this._securityType === "reinforced" ? 8 : 10;

    // We take fence length into account - longer ones have higher priority
    const modifier = Math.min(2, Math.floor(this._fenceLength / 1000));

    return Math.min(10, base + modifier);
  }

  // Implementation of abstract methods
  start(): void {
    if (this._status === "under_maintenance") {
      console.log(`ERROR: Cannot start system ${this._id} - is under maintenance`);
      return;
    }

    this._status = "active";

    // Voltage depends on the security type
    this._voltage = this._securityType === "standard" ? 10000 :
                   this._securityType === "reinforced" ? 20000 : 30000;

    console.log(`Started fence system ${this._id} at location ${this._location}`);
    console.log(`Voltage: ${this._voltage}V, Length: ${this._fenceLength}m`);
  }

  stop(): void {
    this._status = "inactive";
    this._voltage = 0;
    console.log(`Stopped fence system ${this._id} at location ${this._location}`);

    // Reporting an incident at high alert level
    if (SecuritySystem.alertLevel === "high" || SecuritySystem.alertLevel === "critical") {
      SecuritySystem.reportIncident(
        this.systemType,
        this._location,
        `Fence shutdown at high alert level!`
      );
    }
  }

  performReview(): void {
    const previousStatus = this._status;
    this._status = "under_maintenance";
    console.log(`Started fence system review ${this._id}`);

    // Simulation of inspection
    setTimeout(() => {
      this._reviewDate = new Date();
      this._status = previousStatus;
      console.log(`Completed fence system review ${this._id}`);
    }, 2000);
  }

  // Methods specific to this system type
  changeVoltage(newVoltage: number): void {
    if (this._status !== "active") {
      console.log(`ERROR: Cannot change voltage - system is not active`);
      return;
    }

    this._voltage = newVoltage;
    console.log(`Changed fence voltage ${this._id} to ${newVoltage}V`);
  }

  reportFenceBreach(): void {
    this._status = "failure";
    SecuritySystem.reportIncident(
      this.systemType,
      this._location,
      `Electric fence breach detected!`
    );
  }
}

// Another derived class - Video Monitoring System
class VideoMonitoringSystem extends SecuritySystem {
  private _cameraCount: number;
  private _resolution: "SD" | "HD" | "4K";
  private _nightMode: boolean;

  constructor(
    id: string,
    location: string,
    cameraCount: number,
    resolution: "SD" | "HD" | "4K"
  ) {
    super(id, location);
    this._cameraCount = cameraCount;
    this._resolution = resolution;
    this._nightMode = false;
  }

  // Implementation of abstract properties
  get systemType(): string {
    return "Video Monitoring";
  }

  get alarmPriorityLevel(): number {
    // Priority depends on the number of cameras and resolution
    const base = 5;

    // Resolution modifier
    const resolutionModifier =
      this._resolution === "SD" ? 0 :
      this._resolution === "HD" ? 1 : 2;

    // Camera count modifier
    const cameraModifier = Math.min(2, Math.floor(this._cameraCount / 10));

    return Math.min(10, base + resolutionModifier + cameraModifier);
  }

  // Implementation of abstract methods
  start(): void {
    this._status = "active";
    console.log(`Started monitoring system ${this._id} at location ${this._location}`);
    console.log(`Camera count: ${this._cameraCount}, Resolution: ${this._resolution}`);
  }

  stop(): void {
    this._status = "inactive";
    console.log(`Stopped monitoring system ${this._id} at location ${this._location}`);
  }

  performReview(): void {
    this._status = "under_maintenance";
    console.log(`Started monitoring system review ${this._id}`);

    // In this case, the inspection completes immediately
    this._reviewDate = new Date();
    this._status = "active";
    console.log(`Completed monitoring system review ${this._id}`);
  }

  // Methods specific to this system type
  enableNightMode(): void {
    this._nightMode = true;
    console.log(`Enabled night mode in monitoring system ${this._id}`);
  }

  disableNightMode(): void {
    this._nightMode = false;
    console.log(`Disabled night mode in monitoring system ${this._id}`);
  }

  detectMotion(area: string): void {
    console.log(`System ${this._id}: Motion detected in area ${area}`);

    if (SecuritySystem.alertLevel !== "normal") {
      SecuritySystem.reportIncident(
        this.systemType,
        `${this._location} - area ${area}`,
        `Unauthorized motion detected!`
      );
    }
  }
}

// Demonstration of Jurassic Park security system
function testSecuritySystem() {
  console.log("=== INITIALIZING JURASSIC PARK SECURITY SYSTEMS ===");

  // Creating fence systems
  const mainFence = new ElectricFenceSystem("FNC-001", "Sector A - Main entrance", 2500, "ultra-reinforced");
  const tRexFence = new ElectricFenceSystem("FNC-002", "Sector B - T-Rex Enclosure", 1200, "ultra-reinforced");
  const raptorFence = new ElectricFenceSystem("FNC-003", "Sector C - Raptor Enclosure", 800, "reinforced");

  // Creating monitoring systems
  const mainMonitoring = new VideoMonitoringSystem("CAM-001", "Control center", 20, "4K");
  const monitoringTRex = new VideoMonitoringSystem("CAM-002", "Sector B - T-Rex Enclosure", 12, "HD");
  const raptorMonitoring = new VideoMonitoringSystem("CAM-003", "Sector C - Raptor Enclosure", 8, "HD");

  // Starting all systems
  console.log("\n=== STARTING SYSTEMS ===");
  mainFence.start();
  tRexFence.start();
  raptorFence.start();

  mainMonitoring.start();
  monitoringTRex.start();
  raptorMonitoring.start();

  // Starting monitoring
  console.log("\n=== ACTIVATING MONITORING ===");
  mainFence.startMonitoring();
  tRexFence.startMonitoring();
  raptorFence.startMonitoring();

  mainMonitoring.startMonitoring();
  monitoringTRex.startMonitoring();
  raptorMonitoring.startMonitoring();

  // Checking statuses
  console.log("\n=== SYSTEM REPORTS ===");
  console.log(mainFence.generateStatusReport());
  console.log(monitoringTRex.generateStatusReport());

  // Simulating an incident
  console.log("\n=== INCIDENT SIMULATION ===");
  console.log("Current alert level:", SecuritySystem.alertLevel);

  raptorMonitoring.detectMotion("South corner");
  raptorFence.reportFenceBreach();

  // Checking alert level after incidents
  console.log("\nCurrent alert level after incidents:", SecuritySystem.alertLevel);

  // Displaying recent incidents
  console.log("\n=== RECENT INCIDENTS ===");
  SecuritySystem.recentIncidents.forEach((incident, index) => {
    console.log(`${index + 1}. [${incident.date.toLocaleString()}] ${incident.systemType} at ${incident.location}: ${incident.description}`);
  });

  // Conducting inspection
  console.log("\n=== SYSTEM REVIEW ===");
  tRexFence.performReview();
  mainMonitoring.performReview();

  // Manual alert level change
  console.log("\n=== NORMALIZING THE SITUATION ===");
  SecuritySystem.changeAlertLevel("normal");
}

// Running the test
testSecuritySystem();

In this advanced example:

  1. We use the abstract class SecuritySystem as the base for all security systems
  2. The class defines static properties and methods (e.g., park alert level, incident list)
  3. Abstract methods and properties enforce the implementation of specific functionality in derived classes
  4. Derived classes (ElectricFenceSystem and VideoMonitoringSystem) implement the abstract elements
  5. Static elements enable central coordination (e.g., reporting incidents and managing alert levels)

Combining Static and Abstract Elements

Static and abstract elements can be a powerful tool when used together in a well-designed class hierarchy. Here are some patterns and examples of their application:

1. Abstract Base Class with Static Factory Methods

abstract class DinosaurSpecies {
  // Static properties
  private static _registeredSpecies: Map<string, DinosaurSpecies> = new Map();

  // Instance properties
  private _name: string;
  private _era: string;
  protected _dietType: "carnivore" | "herbivorous" | "omnivore";

  constructor(name: string, era: string, diet: "carnivore" | "herbivorous" | "omnivore") {
    this._name = name;
    this._era = era;
    this._dietType = diet;

    // Adding to registry
    DinosaurSpecies._registeredSpecies.set(name, this);
  }

  // Static factory method - creates the appropriate species based on diet
  static createSpecies(
    name: string,
    era: string,
    diet: "carnivore" | "herbivorous" | "omnivore",
    additionalParams: Record<string, any>
  ): DinosaurSpecies {
    if (diet === "carnivore") {
      return new CarnivoreSpecies(
        name,
        era,
        additionalParams.biteForce,
        additionalParams.runSpeed
      );
    } else {
      return new HerbivoreSpecies(
        name,
        era,
        additionalParams.neckLength || 0,
        additionalParams.hasArmor || false
      );
    }
  }

  // Static method for retrieving registered species
  static getSpecies(name: string): DinosaurSpecies | undefined {
    return this._registeredSpecies.get(name);
  }

  static get allSpecies(): string[] {
    return Array.from(this._registeredSpecies.keys());
  }

  // Instance getters
  get name(): string { return this._name; }
  get era(): string { return this._era; }
  get dietType(): string { return this._dietType; }

  // Abstract methods
  abstract describeBehavior(): string;
  abstract estimateWeight(length: number): number;

  // Method using abstract methods
  generateDescription(): string {
    return `${this._name} - ${this._dietType} dinosaur from the ${this._era} era.
${this.describeBehavior()}`;
  }
}

// Derived classes
class CarnivoreSpecies extends DinosaurSpecies {
  private _biteForce: number; // in PSI
  private _runSpeed: number; // in km/h

  constructor(name: string, era: string, biteForce: number, runSpeed: number) {
    super(name, era, "carnivore");
    this._biteForce = biteForce;
    this._runSpeed = runSpeed;
  }

  // Getters
  get biteForce(): number { return this._biteForce; }
  get runSpeed(): number { return this._runSpeed; }

  // Implementation of abstract methods
  describeBehavior(): string {
    return `Hunts at speed ${this._runSpeed} km/h and bite force ${this._biteForce} PSI.`;
  }

  estimateWeight(length: number): number {
    // Approximate formula for predators
    return length * length * 100;
  }
}

class HerbivoreSpecies extends DinosaurSpecies {
  private _neckLength: number; // in meters
  private _hasArmor: boolean;

  constructor(name: string, era: string, neckLength: number, hasArmor: boolean) {
    super(name, era, "herbivorous");
    this._neckLength = neckLength;
    this._hasArmor = hasArmor;
  }

  // Getters
  get neckLength(): number { return this._neckLength; }
  get hasArmor(): boolean { return this._hasArmor; }

  // Implementation of abstract methods
  describeBehavior(): string {
    const neckDescription = this._neckLength > 3
      ? `Has a long neck (${this._neckLength}m) allowing it to eat tall vegetation.`
      : "Feeds on low vegetation.";

    const armorDescription = this._hasArmor
      ? "Has armor for protection against predators."
      : "Has no protective armor.";

    return `${neckDescription} ${armorDescription}`;
  }

  estimateWeight(length: number): number {
    // Approximate formula for herbivores (usually heavier)
    let weight = length * length * 150;

    // Additional weight for armor
    if (this._hasArmor) {
      weight *= 1.3;
    }

    return weight;
  }
}

// Usage
function testDinosaurSpecies() {
  // Creating species using the factory method
  DinosaurSpecies.createSpecies(
    "Tyrannosaurus Rex",
    "late Cretaceous",
    "carnivore",
    { biteForce: 12800, runSpeed: 32 }
  );

  DinosaurSpecies.createSpecies(
    "Velociraptor",
    "late Cretaceous",
    "carnivore",
    { biteForce: 2000, runSpeed: 64 }
  );

  DinosaurSpecies.createSpecies(
    "Brachiosaurus",
    "late Jurassic",
    "herbivorous",
    { neckLength: 9, hasArmor: false }
  );

  DinosaurSpecies.createSpecies(
    "Stegosaurus",
    "late Jurassic",
    "herbivorous",
    { neckLength: 0.5, hasArmor: true }
  );

  // Accessing registered species
  console.log("Available species:", DinosaurSpecies.allSpecies);

  // Retrieving species information
  const trex = DinosaurSpecies.getSpecies("Tyrannosaurus Rex");
  const brach = DinosaurSpecies.getSpecies("Brachiosaurus");

  if (trex) {
    console.log(trex.generateDescription());
    console.log(`Estimated weight (12m long): ${trex.estimateWeight(12)} kg`);
  }

  if (brach) {
    console.log(brach.generateDescription());
    console.log(`Estimated weight (25m long): ${brach.estimateWeight(25)} kg`);
  }

  // Type checking
  const steg = DinosaurSpecies.getSpecies("Stegosaurus") as HerbivoreSpecies;
  if (steg && steg instanceof HerbivoreSpecies) {
    console.log(`Stegosaurus has armor: ${steg.hasArmor ? "YES" : "NO"}`);
  }

  const raptor = DinosaurSpecies.getSpecies("Velociraptor") as CarnivoreSpecies;
  if (raptor && raptor instanceof CarnivoreSpecies) {
    console.log(`Velociraptor - run speed: ${raptor.runSpeed} km/h`);
  }
}

testDinosaurSpecies();

2. Abstract Static Methods

In TypeScript since version 4.0, it's possible to define abstract static methods. This enables creating class hierarchies where derived classes must implement specific static methods:

abstract class LocationSystem {
  // Instance properties
  protected _id: string;
  protected _name: string;

  constructor(id: string, name: string) {
    this._id = id;
    this._name = name;
  }

  // Abstract static method that derived classes must implement
  static abstract generateLocationId(type: string, num: number): string;

  // Regular abstract instance method
  abstract getLocationInfo(): Record<string, any>;

  // Instance method
  generateReport(): string {
    const info = this.getLocationInfo();

    let report = `=== LOCATION REPORT: ${this._name} (ID: ${this._id}) ===\n`;

    for (const [key, value] of Object.entries(info)) {
      report += `${key}: ${value}\n`;
    }

    return report;
  }
}

class DinosaurEnclosure extends LocationSystem {
  private _species: string;
  private _area: number; // in hectares
  private _specimenCount: number;

  constructor(num: number, name: string, species: string, area: number, specimenCount: number) {
    // Generating ID for the enclosure
    const id = DinosaurEnclosure.generateLocationId("enclosure", num);
    super(id, name);

    this._species = species;
    this._area = area;
    this._specimenCount = specimenCount;
  }

  // Implementation of abstract static method
  static generateLocationId(type: string, num: number): string {
    return `${type.toUpperCase()}-${num.toString().padStart(3, '0')}`;
  }

  // Implementation of abstract instance method
  getLocationInfo(): Record<string, any> {
    return {
      type: "Dinosaur enclosure",
      species: this._species,
      area: `${this._area} ha`,
      specimenCount: this._specimenCount,
      populationDensity: `${(this._specimenCount / this._area).toFixed(2)} spec./ha`
    };
  }

  // Methods specific to this class
  addSpecimen(): void {
    this._specimenCount++;
    console.log(`Added new specimen to enclosure ${this._name}. New count: ${this._specimenCount}`);
  }

  removeSpecimen(): boolean {
    if (this._specimenCount > 0) {
      this._specimenCount--;
      console.log(`Removed specimen from enclosure ${this._name}. New count: ${this._specimenCount}`);
      return true;
    }

    console.log(`Error: Cannot remove specimen from enclosure ${this._name} - no specimens.`);
    return false;
  }
}

class TouristAttraction extends LocationSystem {
  private _attractionType: string;
  private _capacity: number;
  private _waitTime: number; // in minutes

  constructor(num: number, name: string, attractionType: string, capacity: number) {
    // Generating ID for the attraction
    const id = TouristAttraction.generateLocationId("attraction", num);
    super(id, name);

    this._attractionType = attractionType;
    this._capacity = capacity;
    this._waitTime = 0;
  }

  // Implementation of abstract static method
  static generateLocationId(type: string, num: number): string {
    // Different ID format for attractions
    return `${type.substring(0, 3).toUpperCase()}${num.toString().padStart(4, '0')}`;
  }

  // Implementation of abstract instance method
  getLocationInfo(): Record<string, any> {
    return {
      type: "Tourist attraction",
      category: this._attractionType,
      capacity: this._capacity,
      waitTime: `${this._waitTime} min`
    };
  }

  // Methods specific to this class
  updateWaitTime(newWaitTime: number): void {
    this._waitTime = newWaitTime;
    console.log(`Updated wait time for ${this._name}: ${this._waitTime} min`);
  }
}

// Application
function testLocationSystem() {
  // Creating enclosures
  const tRexEnclosure = new DinosaurEnclosure(1, "T-Rex Kingdom", "Tyrannosaurus Rex", 5, 1);
  const raptorEnclosure = new DinosaurEnclosure(2, "Raptor Valley", "Velociraptor", 3, 6);

  // Creating attractions
  const visitorCenter = new TouristAttraction(101, "Genetics Center", "educational", 500);
  const jeepSafari = new TouristAttraction(102, "Jurassic Safari", "ride", 50);

  // Displaying reports
  console.log(tRexEnclosure.generateReport());
  console.log(raptorEnclosure.generateReport());
  console.log(visitorCenter.generateReport());
  console.log(jeepSafari.generateReport());

  // Performing operations
  raptorEnclosure.addSpecimen();
  raptorEnclosure.addSpecimen();
  jeepSafari.updateWaitTime(45);

  // Checking updated data
  console.log(raptorEnclosure.generateReport());
  console.log(jeepSafari.generateReport());

  // Demonstration of different ID formats generated by static method implementations
  console.log("Enclosure ID format:", DinosaurEnclosure.generateLocationId("enclosure", 42));
  console.log("Attraction ID format:", TouristAttraction.generateLocationId("attraction", 42));
}

testLocationSystem();

Summary

In this exercise, we learned about two powerful TypeScript mechanisms:

  1. Static properties and methods:

    • Belong to the class, not to instances
    • Enable sharing data and functionality between all instances
    • Ideal for defining constants, global state, and utility methods
    • Accessible directly through the class name, without creating instances
  2. Abstract classes and methods:

    • Define a "template" or "contract" that must be implemented by inheriting classes
    • Cannot be instantiated directly
    • Enforce the implementation of specific methods in derived classes
    • Allow sharing common functionality through a class hierarchy

By combining these concepts, we can create elegant, modular, and type-safe systems that are ideal for modeling complex relationships and processes, such as those in the Jurassic Park management system.

Dr. Henry Wu would summarize it as follows: "In nature, as in programming, there is beauty in structure and order. Static elements ensure consistency for the entire species, while abstract concepts form the basic blueprint that each organism must implement in its own way. Together they create perfect harmony - with proper safeguards, of course... in most cases."

Code for this lesson: index.ts
// Static properties and abstract classes - Jurassic Park
console.log("=== STATIC PROPERTIES AND ABSTRACT CLASSES ===\n");

// ===========================================
// 1. The abstract class Dinosaur
// ===========================================

abstract class Dinosaur {
  // Static counter for all dinosaurs
  static totalCount: number = 0;
  static readonly PARK_NAME: string = "Jurassic World";

  // Static factory method
  static createId(): string {
    return `DINO-${String(++Dinosaur.totalCount).padStart(4, "0")}`;
  }

  // Instance fields
  readonly id: string;
  name: string;
  protected weight: number;

  constructor(name: string, weight: number) {
    this.id = Dinosaur.createId();
    this.name = name;
    this.weight = weight;
  }

  // Abstract method - each species must implement it
  abstract makeSound(): string;
  abstract getDangerLevel(): number;

  // Common method
  getProfile(): string {
    return `[${this.id}] ${this.name} - ${this.weight}kg`;
  }
}

// ===========================================
// 2. Implementations of concrete classes
// ===========================================

class TRex extends Dinosaur {
  private biteForce: number;

  constructor(name: string, weight: number, biteForce: number) {
    super(name, weight);
    this.biteForce = biteForce;
  }

  makeSound(): string {
    return "ROOOOAAAR!";
  }

  getDangerLevel(): number {
    return 10;
  }
}

class Triceratops extends Dinosaur {
  private hornLength: number;

  constructor(name: string, weight: number, hornLength: number) {
    super(name, weight);
    this.hornLength = hornLength;
  }

  makeSound(): string {
    return "BRRRRR!";
  }

  getDangerLevel(): number {
    return 4;
  }
}

// ===========================================
// 3. Static factory method
// ===========================================

class DinosaurFactory {
  static registry: Map<string, Dinosaur> = new Map();

  static create(type: "trex" | "triceratops", name: string): Dinosaur {
    let dino: Dinosaur;
    if (type === "trex") {
      dino = new TRex(name, 8000, 12800);
    } else {
      dino = new Triceratops(name, 6000, 90);
    }
    DinosaurFactory.registry.set(dino.id, dino);
    return dino;
  }

  static getAll(): Dinosaur[] {
    return Array.from(DinosaurFactory.registry.values());
  }
}

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

const rex = DinosaurFactory.create("trex", "Rexy");
const trike = DinosaurFactory.create("triceratops", "Cera");
const rex2 = DinosaurFactory.create("trex", "Buck");

console.log("Park:", Dinosaur.PARK_NAME);
console.log("Number of dinosaurs:", Dinosaur.totalCount);
console.log("");

DinosaurFactory.getAll().forEach(dino => {
  console.log(dino.getProfile());
  console.log("  Sound:", dino.makeSound());
  console.log("  Danger:", dino.getDangerLevel(), "/10");
});

// You cannot create an instance of an abstract class:
// const dino = new Dinosaur("Test", 100); // Error!
console.log("\nAn abstract class cannot be instantiated directly.");

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. What is an abstract class in TypeScript?

  2. 2. How do static properties differ from regular ones in a class?

Hands-on tasks in the game

  • Code editor

    Implement classes with static and abstract properties.

  • Click in order

    Arrange the elements of an abstract class declaration:

  • Code editor

    Create classes with different access modifiers for the park system

  1. QuestionAbstract Classes
  2. Coding taskPractice: Static and Abstract
  3. QuestionStatic Properties
  4. Click in orderSorting: Abstract Class Syntax
  5. Coding taskAccess Modifiers - Practice

Useful articles